Daniel T.
Daniel T.

Reputation: 38390

How do I map a small object graph using Entity Framework Code First 4.1?

I have a very small object graph that I'm using:

public struct Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    etc...
}

public class User
{
    public Address HomeAddress { get; set; }
    public Address WorkAddress { get; set; }
    public string FirstName { get; set; }
    etc...
}

Using Entity Framework 4.1, how would I map this structure to one table so that they're mapped to columns like:

HomeAddressLine1
HomeAddressLine2
WorkAddressLine1
WorkAddressLine2
FirstName
LastName
etc...

Upvotes: 0

Views: 254

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

EF doesn't support structures. You must use class for your Address and map it as complex type:

public class Address
{
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
}

public class User
{
    public int Id { get; set; }
    public Address HomeAddress { get; set; }
    public Address WorkAddress { get; set; }
    public string FirstName { get; set; }
}


public class Context : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    {
        modelBuilder.Entity<User>()
                    .Property(u => u.HomeAddress.AddressLine1)
                    .ColumnName("HomeAddressLine1");
        // Use the same pattern for all columns of HomeAddress and WorkAddress
    }
}

Upvotes: 1

Related Questions