Home > dotnet 4, Entity Framework > POCO and Entity Framework:Using Complex Types

POCO and Entity Framework:Using Complex Types

In September last year I did a quick tutorial about POCO and Entity Framework thinking that it is in CTP 4 and is about to be released. Apparently that wasn’t the case and now it’s in CTP 5 with a promise from Microsoft that we all will have a go license by March end, so I thought I will update my code with CTP 5 changes and will introduce some real life project scenarios as well.

Scenario 1: We want to create a Customer table from the previous post sample and want to add some address related column to the database but we want to map this Address as a complex type in our model. This way we are creating a conceptual model which is different than the the database model and this is how we want the database table to look like.

Customer Table

and this is how the two classes look like in a class diagram.

Customer and Address class diagram

and the code

Customer.cs

public class Customer
{
    public string CustomerId { get; set; }
    public string CompanyName { get; set; }
    public string ContactName { get; set; }
    public string ContactTitle { get; set; }
    public Address Address { get; set; }
    public string City { get; set; }
    public string Region { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string Fax { get; set; }
}

 

Address.cs

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string Suburb { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
}

Now lets write the configuration file for customer where we will specify different attributes of this class and which the model builder class will configure to create our table in the database.

public class CustomerConfiguration  : EntityTypeConfiguration<Customer>
{
    public CustomerConfiguration()
    {
        this.HasKey(c => c.CustomerId);
        this.Property(c => c.ContactName).IsRequired();
    }
}

As you can see there is a slight change from CTP4 to CTP5 as the configuration base class has changed from EntitiyConfiguration to EntityTypeConfiguration and now lets put it all together in our DbContext class.

POCOContext.cs

public class POCOContext : DbContext
{
    public DbSet<Customer> Customer { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CustomerConfiguration());
        modelBuilder.ComplexType<Address>();
    }
}

And what’s the point of writing code if we are not going to write a unit test so lets go ahead and write a simple unit test which will create the POCOContext database and the customer table.

Unit Test

[TestClass()]
public class When_using_POCOContext
{
    [TestMethod()]
    public void Should_be_able_to_create_POCOContext_database()
    {
        var target = new POCOContext();
        target.Database.Initialize(true);
    }

}

and in order to run this test properly and the creation of the database lets add the application configuration file to the test project and add the connection string.

App.config

<connectionStrings>
  <
add name="POCOContext"
       connectionString="Data Source=.\SQLEXPRESS; Initial Catalog=POCO; Integrated Security=True;"
       providerName="System.Data.SqlClient"
/>
</
connectionStrings
>

and when we open the table in design mode we can see it creates the table with the complex type embedded in it.
Customer Table Definition

The beauty about EF Code first is that the code is very clean, simple classes with one single responsibility. There are no messy XML file, modeling classes, definition files etc and can be replaced with new models with out messing up with any files.

I hope you liked it and in coming days I ‘ll be covering some other scenarios as well.

Advertisements
  1. arkhan
    November 30, 2011 at 9:55 am

    just curious about what’s the benefit of having a complex type rather than an entity type?

    • December 19, 2011 at 8:21 pm

      Hi,
      Complex type are just classes which have a meaning in your domain but not necessary they map to a physical table. Like in our instance in our domain we have address which is an entity in the customer class but in the database there is no address table.

  2. Vinay
    April 25, 2012 at 5:51 am

    Hi Prashant,
    Gud stuff to learn from your blog.Right now I am working with code first approach.I have doubt As you explained above I have two tables not a single table those are Person and Address.
    I have no primary key for Address table.As shown in the above fig.I have the exact table structures Person and Address.I need to map those tables how I need to map If I am doing as you said above using complex type i am unable to solve my problem.Pls let me know how I need to map those tables.

    • May 3, 2012 at 8:56 pm

      Hi Vinay,
      The complex type is like a logical entity which exists in your domain model but not in a physical table. If you have a physical table then it must have the Person_Id column in it otherwise you won’t be able to relate the two.

      Try adding the Person type in your Address entity and generate a new database to see whether it gives you desired structure. If not try other techniques I have shown in EF Code first posts.

      • Vinay
        May 4, 2012 at 5:15 pm

        hi prashanth thanks for your reply..I will tell my columns Person table->Id,Name
        and in Address table personId,Address,City.In entity how i need to map both.

  3. anshul1007
    January 16, 2013 at 5:07 pm

    Hi Prashant,

    I am new to EF and your posting is helping a lot to me to learn EF. I have a doubt, I want minimal database hits, so I wrote store proc which returns data from two different tables. So there is any way to load this output in different entities?

  4. Visitar Pagina
    June 28, 2013 at 6:56 am

    There’s certainly a lot to know about this issue. I like all the points you made.

  5. beastiality
    July 12, 2013 at 11:40 am

    I believe this is one of the such a lot vital information for me.
    And i am happy reading your article. However wanna observation on few common things, The website taste is wonderful, the articles is in point of fact excellent : D.
    Just right process, cheers

  6. July 16, 2013 at 6:43 am

    Heya just wanted to give you a brief heads
    up and let you know a few of the images aren’t loading properly. I’m not sure
    why but I think its a linking issue. I’ve tried it in two different browsers and both show the same outcome.

  7. priscillagerow
    November 3, 2014 at 8:56 am

    It’s really a nice and useful piece of info. I’m glad that you simply shared this
    helpful information with us. Please stay us up to date like this.
    Thank you for sharing.

    • November 7, 2014 at 6:52 am

      Thanks priscillagerow it’s comments like this makes me blog more and I hope to continue writing good post.

  1. March 23, 2011 at 8:05 am
  2. May 8, 2014 at 7:14 pm
    Jon

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: