如何使用Entity Framework Code First 4.1映射小对象图?

时间:2012-06-13 02:59:56

标签: entity-framework entity-framework-4.1 ef-code-first

我正在使用一个非常小的对象图:

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...
}

使用Entity Framework 4.1,我如何将此结构映射到一个表,以便它们映射到如下列:

HomeAddressLine1
HomeAddressLine2
WorkAddressLine1
WorkAddressLine2
FirstName
LastName
etc...

1 个答案:

答案 0 :(得分:1)

EF不支持结构。您必须使用您的地址类并将其映射为复杂类型:

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
    }
}