Complex Types in the EDM Designer in EF4 and a look at updating complex types in code

Previous "What's New in EF 4 Posts"

ef4

 

One of the great features of an EF Entity Data Model is the complex type. However, the designer in VS2008 SP1 does not support ComplexTypes which is a big shame. You can manually modified the model to add a complex type into it, but alas, this would render the model unreadable to the designer and you would no longer be able to open the model up in design view.

In VS2010, there have been a lot of improvements to the designer and complex type support is one of them. Here is a quick rundown of how it works.

I have a person type with FirstName and LastName. I want to encapsulate those properties into a single complex type called name and make that type be a property of person.

In the new designer you can refactor the properties on the fly by highlighting the desired properties, right clicking and then choosing Refactor into New Complex Type in the context menu.

complexa

The result is a new property

complexb

which you can rename. Here I have changed the name of ComplexProperty to Name.

complexc

The designer has fixed up the mappings for you. The FirstName column from the db table is now mapped to the property Name.FirstName. LastName is also properly mapped.

complexd

What about Querying and updating?

The complex type property is automatically materialized as part of the Person entity when you query the data.

Here you can see Intellisense providing Name.LastName and Name. FirstName. Also note that the ComplexType gets change-tracked ...you can see the PropertyChanged and PropertyChanging events are part of the Name type.

 

complexe

 

An interesting thing about updating is that all of the fields of the complex type are updated, not just the changed field. This is different behavior than how EF normally handles property changes. But it is expected behavior for complex types.

person.Name.LastName = "Le Pew"; context.SaveChanges();

Here is the TSQL showing that the first name was also sent up to save
exec sp_executesql N'update [dbo].[Person]set [FirstName] = @0, [LastName] = @1where ([PersonID] = @2)',N'@0 nchar(50),@1 nchar(50),@2 int',
@0=N'Pepe',
@1=N'Le Pew',
@2=1

 

This made me check to see what happens if I modified one of the scalar properties of Person. Would the complex type values be passed in? The answer is no.  That behaves normally.

I updated Person.Title

person.Title = "Msr.";context.SaveChanges();

which is the only field that was passed up for editing. The complex type fields only get sent up if one of them was modified.

Here's the TSQL.

exec sp_executesql N'update [dbo].[Person]set [Title] = @0where ([PersonID] = @1)',N'@0 nchar(50),@1 int',
@0=N'Msr.',
@1=1

No comments (yet...)

Leave a Comment