LOG IN

Forgot Your Password?


Incorrect login or password

SIGN UP



Existing user?

Forgot Password


Existing user?

Creating Complex Types in Entity Framework

Creating Complex Types in Entity Framework

The following post will Creating Complex Types in Entity Framework
explain what are complex
types
in Entity Framework
and how to use them.

What are Complex Types?

Complex types are a way to encapsulate a set of entity’s properties inside a
structure which isn’t an entity. You use them to organize properties into
structures that make your design more understandable. For example, you
can have a Customer entity which has properties that make an address. 
You can arrange these properties in a Address complex type. Complex types
are a conceptual entities types. You build them in the CSDL and
map them to properties in the MSL.
Some points to be considered when using complex types:

  • Complex types cannot exist without a parent entity or another
    containing complex type.
  • Complex types are not supported in the current version of
    Entity Framework’s designer. Using the Update Model form
    Database feature will erase the manually changes of the complex
    type
    .
  • Complex type properties cannot be null.
  • You can’t use inheritance with complex types.
  • A change to one property of a complex type will cause an update
    to the entire complex type when SaveChanges method is called.

How to Use Complex Types in Code?

In the example I’m going to build a CourseDetails complex type inside
a Course entity. The recipe for building other complex types is the same.

Step 1
Open the model in a Xml editor and search for the CSDL part. Search
the entity that you want to build a complex type inside of it. In my example
the entity is Course:

<EntityType Name="Course">
  <Key>
    <PropertyRef Name="CourseID" />
  </Key>
  <Property Name="CourseID" Type="Int32" Nullable="false" />
  <Property Name="Title" Type="String" Nullable="false" MaxLength="100" Unicode="true" FixedLength="false" />
  <Property Name="Days" Type="String" Nullable="false" />
  <Property Name="Time" Type="DateTime" Nullable="false" />
  <Property Name="Location" Type="String" Nullable="true" />
  <Property Name="Credits" Type="Int32" Nullable="false" />
  <NavigationProperty Name="Department" Relationship="SchoolModel.FK_Course_Department" FromRole="Course" ToRole="Department" />
  <NavigationProperty Name="Enrollment" Relationship="SchoolModel.FK_Enrollment_Course" FromRole="Course" ToRole="Enrollment" />
  <NavigationProperty Name="Person" Relationship="SchoolModel.CourseInstructor" FromRole="Course" ToRole="Person" />
</EntityType>

Step 2

Copy the properties which will belong to the complex type and delete them

from the entity. Then, add a new property which will have the new complex

type
’s type. The following is the new Course entity after adding the

CourseDetails complex type:

<EntityType Name="Course">
  <Key>
    <PropertyRef Name="CourseID" />
  </Key>
  <Property Name="CourseID" Type="Int32" Nullable="false" />
  <Property Name="Title" Type="String" Nullable="false" MaxLength="100" Unicode="true" FixedLength="false" />
  <Property Name="CourseDetails" Type="Self.CourseDetails" Nullable="false" />
  <NavigationProperty Name="Department" Relationship="SchoolModel.FK_Course_Department" FromRole="Course" ToRole="Department" />
  <NavigationProperty Name="Enrollment" Relationship="SchoolModel.FK_Enrollment_Course" FromRole="Course" ToRole="Enrollment" />
  <NavigationProperty Name="Person" Relationship="SchoolModel.CourseInstructor" FromRole="Course" ToRole="Person" />
</EntityType>

Step 3

Add a new complex type to the CSDL and copy the saved properties to it.

<ComplexType Name="CourseDetails" >
  <Property Name="Days" Type="String" Nullable="false" />
  <Property Name="Time" Type="DateTime" Nullable="false" />
  <Property Name="Location" Type="String" Nullable="true" />
  <Property Name="Credits" Type="Int32" Nullable="false" />
</ComplexType>

Step 4

In the MSL, add a ComplexProperty inside the EntityTypeMapping of

your entity and insert the properties of the complex type inside of it.

<EntitySetMapping Name="Course">
    <EntityTypeMapping TypeName="IsTypeOf(SchoolModel.Course)">
      <MappingFragment StoreEntitySet="Course">
        <ScalarProperty Name="CourseID" ColumnName="CourseID" />
        <ScalarProperty Name="Title" ColumnName="Title" />
        <ComplexProperty Name="CourseDetails" TypeName="SchoolModel.CourseDetails">
          <ScalarProperty ColumnName="Days" Name="Days"/>
          <ScalarProperty ColumnName="Time" Name="Time" />
          <ScalarProperty ColumnName="Location" Name="Location" />
          <ScalarProperty ColumnName="Credits" Name="Credits" />
        </ComplexProperty>
      </MappingFragment>
    </EntityTypeMapping>
</EntitySetMapping>

And that’s it.

Step 5

Test the new mapping. The following code is a test program I wrote

to test the new CourseDetails complex type:

class Program
{
    static void Main(string[] args)
    {
        using (SchoolEntities context = new SchoolEntities())
        {
            Course course = new Course
            {
                CourseDetails = new CourseDetails
                {
                    Credits = 3,
                    Days = "MF",
                    Location = "Class A",
                    Time = DateTime.Now
                },
                Title = "New Course",
                Department = context.Department.First()
            };
 
            context.AddToCourse(course);
            context.SaveChanges();
 
            var newCourse = (from c in context.Course
                             where c.Title == "New Course"
                             select c).First();
 
            Console.WriteLine("{0}", newCourse.CourseDetails.Time);
            Console.ReadLine();
        }            
    }
}

The test program creates a new course and insert it to the

database. After that it retrieve that course and print to the output

the Time property which will hold the current time.

Summary

Lets sum up, today I explained what are complex types and how to

use them in Entity Framework. The use of complex types can help

you organize your design and to build CSDL structures which you

need. Pay attention to the restrictions that I wrote about they can have

an impact on your model’s design.

source: http://blogs.microsoft.co.il/gilf/2009/04/02/creating-complex-types-in-entity-framework/


 << Previous  Next >>