Entity Framework Mapping – Complex Type Properties

Another very flexible Entity Framework mapping feature, besides table splitting and entity splitting, is the use of complex type properties. These come into play when we want to group certain properties together to better mold and organize our model to our needs.

In the example below we have a Fan (of an artist) entity.

Entity Framework Fan Model

Now this entity has a lot of properties related to the name of the person. We can ‘merge’ them into a complex type. This way all name related properties are grouped together in the entity. To do this we select all properties we want to include into this complex type. Right click and select “Refactor into New Complex Type”. We see our newly created complex type in the model browser and name it FanName.

Entity Framework Model Browser Complex Types

We also need to change the name of the complex type property (of type FanName) into ‘Name’ to make it more defining. Note the icon of the complex type property has a distinct character.

Entity Framework Model Complex Type

So now we can use the complex type property in our code as follows.

using System;
using System.Linq;
using Entities;
 
namespace MusicConsole
{
    internal class Program
    {
        private static void Main()
        {
            using (var context = new MusicModelContainer())
            {
                IQueryable<Fan> query = 
                    context.Fans.Where(f => f.Name.FirstName.Equals("Bob"));
 
                foreach (Fan fan in query)
                {
                    Console.WriteLine(fan.Name.SurName);
                }
            }
        }
    }
}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>