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.
and this is how the two classes look like in a class diagram.
and the code
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.
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.
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.
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.
and when we open the table in design mode we can see it creates the table with the complex type embedded in it.
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.