Entity Framework - Reuse Complex Type

陌路散爱 提交于 2019-12-18 06:09:07

问题


I have an Entity in Code First Entity framework that currently looks like this:

public class Entity
{
    // snip ...

    public string OriginalDepartment { get; set; }
    public string OriginalQueue { get; set; }

    public string CurrentDepartment { get; set; }
    public string CurrentQueue { get; set; }
}

I would like to create Complex Type for these types as something like this:

public class Location
{
    public string Department { get; set; }
    public string Queue { get; set; }
}

I'd like to use this same type for both Current and Original:

public Location Original { get; set; }
public Location Current { get; set; }

Is this possible, or do I need to create two complex types CurrentLocation and OriginalLocation?

public class OriginalLocation
{
    public string Department { get; set; }
    public string Queue { get; set; }
}

public class CurrentLocation
{
     public string Department { get; set; }
     public string Queue { get; set; }
}

回答1:


It is supported out of box, you do not need to create two complex types.

You can also configure your complex types explicitely with model builder

modelBuilder.ComplexType<Location>();

To customize column names, you should configure them from parent entity configuration

public class Location
{
    public string Department { get; set; }
    public string Queue { get; set; }
}

public class MyEntity
{
    public int Id { get; set; }
    public Location Original { get; set; }
    public Location Current { get; set; }
}

public class MyDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.ComplexType<Location>();

        modelBuilder.Entity<MyEntity>().Property(x => x.Current.Queue).HasColumnName("myCustomColumnName");
    }
}

This will map MyEntity.Current.Queue to myCustomName column



来源:https://stackoverflow.com/questions/9931341/entity-framework-reuse-complex-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!