Entity Framework can have in its EDMX file complex entities. The “normal” property of an entity is a “Scalar entity”.
Scalar entity is a property of the CLR type.
The complex entity is not a CLR type. In fact, it’s a group of scalar entities. From the point of view of the database, nothing change either if it’s a complex or scalar property. But, from the point of view of the Object Context, the entity will have an object with a group of scalar property.
How to add Complex entity?
In the AdventureWorks database once the model is generated from the database you get tables, views and stored procedure. For this exercise, lets take the generated entity “Department”
DepartmentID, Name, GroupName and ModifiedDate are all scalar entities. If we want to add a Complex Entity, we need to add a complex type that will be added to the entity. To add a complexe type, right-click the Visual Designer and select Add>Complex Type.
One the complexe type is created, this one will be added in the Model Browser under the Entity Model (.edmx file), under the folder “Complex types”. From there, it’s possible to right click the complex entity to add scalar entity or even other complex entity.
Once the complex type is created, it’s possible to add it as a complex property. Right clicking on the entity and selecting add and complex property. The last step is to select the complex property and to go to the property window to select the type of the created type.
From here, it’s possible to access the complex property and will be even in the Intellisense.
var db = new AdventureWorks_DataEntities(); var aSingleDepartment = db.DepartmentList.Where(dept => dept.DepartmentID == 1).FirstOrDefault<Department>(); int theIntegerPropertyOfMyComplexPropertyOfDepartment = aSingleDepartment.MyComplexProperty.MyFirstIntProperty;
The only thing that remain to do before compiling is a last mapping for the complex entity. This is needed because you will receive an error message if not.
Error 3004: Problem in mapping fragments starting at line 5050: No mapping specified for properties Department.
MyComplexProperty in Set DepartmentList.
An Entity with Key (PK) will not round-trip when: Entity is type [AdventureWorks_DataModel.Department]
This last step is concerning the mapping with the database.
What about the database? Well, once the entity is modified in the entity model, it requires to be synchronized with the database. This is done by right clicking the Visual Designer and selecting “Generate database model from model”. This will override the DDL file (Data Definition Language), the SSDL (Store schema definition language) and the MSL (Mapping Specification Language) files.