Associations in EF Code First: Part 2 – Complex Types
This is the second post in a series that explains entity association mappings with EF Code First. This series includes:
Introducing the ModelFirst, let's review the model that we are going to use in order to create a Complex Type with EF Code First. It's a simple object model which consists of two classes: User and Address. Each user could have one billing address (or nothing at all–note the multiplicities on the class diagram). The Address information of a User is modeled as a separate class as you can see in the class diagram below: |
In object-modeling terms, this association is a kind of aggregation—a part-of relationship. Aggregation is a strong form of association; it has some additional semantics with regard to the lifecycle of objects. In this case, we have an even stronger form, composition, where the lifecycle of the part is fully dependent upon the lifecycle of the whole.
Fine-grained Domain ModelsThe motivation behind this design was to achieve Fine-grained domain models. In crude terms, fine-grained means more classes than tables. For example, a user may have both a billing address and a home address. In the database, you may have a single Users table with the columns BillingStreet, BillingCity, and BillingZipCode along with HomeStreet, HomeCity, and HomeZipCode. There are good reasons to use this somewhat denormalized relational model (performance, for one). In our object model, we can use the same approach, representing the two addresses as six string-valued properties of the User class. But it’s much better to model this using an Address class, where User has the BillingAddress and HomeAddress properties. This object model achieves improved cohesion and greater code reuse and is more understandable.Complex Types are Objects with No IdentityWhen it comes to the actual C# implementation, there is no difference between this composition and other weaker styles of association but in the context of ORM, there is a big difference: A composed class is often a candidate Complex Type (aka Value Object). But C# has no concept of composition—a class or property can’t be marked as a composition. The only difference is the object identifier: a complex type has no individual identity (e.g. there is no AddressId defined on Address class) which make sense because when it comes to the database everything is going to be saved into one single table.Complex Type DiscoveryCode First has a concept of Complex Type Discovery that works based on a set of Conventions. The convention is that if Code First discovers a class where a primary key cannot be inferred, and no primary key is registered through Data Annotations or the fluent API, then the type will be automatically registered as a complex type. Complex type detection also requires that the type does not have properties that reference entity types (i.e. all the properties must be scalar types) and is not referenced from a collection property on another type.How to Implement a Complex Type with EF Code FirstThe following shows the implementation of the introduced model in Code First: |
public class User { public int UserId { get; set; } public string Name { get; set; } public Address Address { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } public class Context : DbContext { public DbSet<User> Users { get; set; } } |
With code first, this is all of the code we need to write to create a complex type, we do not need to configure any additional database schema mapping information through Data Annotations or the fluent API.
Complex Types: Splitting a Table Across Multiple TypesThe mapping result for this object model is as follows (Note how Code First prefixes the complex type's column names with the name of the complex type): |
Complex Types are RequiredAs a limitation of EF in general, complex types are always considered required. To see this limitation in action, let's try to add a record to the Users table: |
using (var context = new Context()) { User user = new User() { Name = "Morteza" }; context.Users.Add(user); context.SaveChanges(); } |
Surprisingly, this code throws a System.Data.UpdateException at runtime with this message: |
Null value for non-nullable member. Member: 'Address'. |
If we initialize the address object, the exception would go away and the user will be successfully saved into the database: |
Now if we read back the inserted record from the database, EF will return an Address object with Null values on all of its properties (Street, City and ZipCode). This means that even when you store a complex type object with all null property values, EF still returns an initialized complex type when the owning entity (e.g. User) is retrieved from the database. |
Explicitly Register a Type as ComplexYou saw that in our model, we did not use any data annotation or fluent API code to designate the Address as a complex type, yet Code First detects it as a complex type based on Complex Type Discovery. But what if our domain model requires a new property like "Id" on Address class? This new Id property is just another scalar non-primary key property that represents let's say another piece of information about Address. Now Code First can (and will) infer a key and therefore marks Address as an entity that has its own mapping table unless we specify otherwise. This is where explicit complex type registration comes into play. There are two ways to register a type as complex: |
[ComplexType] public class Address { public string Id { get; set; } public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } |
This will keep Address as a complex type in our model despite its Id property. |
|
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.ComplexType<Address>(); } |
Best Practices When Working with Complex Types
|
public class User { public User() { Address = new Address(); } public int UserId { get; set; } public string Name { get; set; } public Address Address { get; set; } } [ComplexType] public class Address { public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } public bool HasValue { get { return (Street != null || ZipCode != null || City != null); } } } |
The interesting point is that we did not have to explicitly exclude the HasValue property from the mapping above. Since HasValue has been defined as a read only property (i.e. there is no setter), EF Code First will be ignoring it based on conventions, which makes sense since a read only property is most probably representing a computed value and does not need to be persisted in the database. |
Customize Complex Type's Property Mappings at Entity LevelWe can customize the individual property mappings of the complex type. For example, The Users table now contains, among others, the columns Address_Street, Address_PostalCode, and Address_City. We can rename these with ColumnAttribute: |
public class Address { [Column("Street")] public string Street { get; set; } public string City { get; set; } public string PostalCode { get; set; } } |
Fluent API can give us the same result as well: |
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.ComplexType<Address>() .Property(a => a.Street) .HasColumnName("Street"); } |
Any other entity table that contains complex type fields (say, a Customer class that also has an Address) uses the same column options. Sometimes we’ll want to override the settings we made inside the complex type from outside for a particular entity. This is often the case when we try to derive an object model from a legacy database. For example, here is how we can rename the Address columns for Customer class: |
public class User { public int UserId { get; set; } public string Name { get; set; } public Address Address { get; set; } } public class Customer { public int CustomerId { get; set; } public string PhoneNumber { get; set; } public Address Address { get; set; } } [ComplexType] public class Address { [Column("Street")] public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } public class Context : DbContext { public DbSet<User> Users { get; set; } public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Customer>() .Property(c => c.Address.Street) .HasColumnName("Customer_Street"); } } |
Complex Types and the New Change Tracking APIAs part of the new DbContext API, EF 4.1 came with a new set of change tracking API that enables us to access Original and Current values of our entities. The Original Values are the values the entity had when it was queried from the database. The Current Values are the values the entity has now. This feature also fully supports complex types.The entry point for accessing the new change tracking API is DbContext's Entry method which returns an object of type DbEntityEntry. DbEntityEntry contains a ComplexProperty method that returns a DbComplexPropertyEntry object where we can access the original and current values: |
using (var context = new Context()) { var user = context.Users.Find(1); Address originalValues = context.Entry(user) .ComplexProperty(u => u.Address) .OriginalValue; Address currentValues = context.Entry(user) .ComplexProperty(u => u.Address) .CurrentValue; } |
Also we can drill down into the complex object and read or set properties of it using chained calls: |
string city = context.Entry(user)
.ComplexProperty(u => u.Address)
.Property(a => a.City)
.CurrentValue; |
We can even get the nested properties using a single lambda expression: |
string city = context.Entry(user)
.Property(u => u.Address.City)
.CurrentValue; |
Limitations of This MappingThere are three important limitations to classes mapped as Complex Types:SummaryIn this post we learned about fine-grained domain models which complex type is just one example of it. Fine-grained is fully supported by EF Code First and is known as the most important requirement for a rich domain model. Complex type is usually the simplest way to represent one-to-one relationships and because the lifecycle is almost always dependent in such a case, it’s either an aggregation or a composition in UML. In the next posts we will revisit the same domain model and will learn about other ways to map a one-to-one association that does not have the limitations of the complex types.References |