Entity Framework 4.1 – Component mapping

By default if you add ‘simple’ property types to your class (strings, ints,…), they are all translated into columns in the database. What if you had a group of properties that actually can have some functionality together. You also have this group of properties coming back at several places in your code base. You could introduce a base class in order to improve duplication but if the two entities are not really related you should stay away from overusing the inheritance approach. What you need here is a complextype. It was present in previous releases of the Entity Framework and can be used in 4.1.

We’ll modify the customer class posted below into something a bit more object oriented.

    public class Customer
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
    }

Customer could also have a bunch of methods that acted upon the address fields, Employee could have the same properties, the same logic and an invoice probably also has an address. So let’s move the properties, and logic, into a new class called Address. I don’t want a separate table that contains all the addresses though, I want all of the address fields to be present in the customer, employee and invoice table.

In order to achieve that result you need the ComplexType attribute.

    public class Customer
    {
        public Customer()
        {
            Address = new Address();
        }
 
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
    }
 
    [ComplexType]
    public class Address
    {
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
    }

Using the ComplexType attribute will result in a database table with the correct structure.

You can also use the fluent API to configure a complextype.

    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.ComplexType<Address>();
            base.OnModelCreating(modelBuilder);
        }
 
    }

2 Replies to “Entity Framework 4.1 – Component mapping”

  1. And how would you then introduce a foreign key from Address_Country to a distinct Country entity?

    1. Not supported. If you’d add a Country class to the example, which you can, they’ll also be mapped directly into the Customer table. You’d get columns like Address_Country_Name. Maybe next release :).

Leave a Reply

Your email address will not be published. Required fields are marked *