实体框架-重用复杂类型

本文关键字:复杂 类型 -重 框架 实体 | 更新日期: 2023-09-27 18:29:22

我在代码优先实体框架中有一个实体,目前看起来像这样:

public class Entity
{
    // snip ...
    public string OriginalDepartment { get; set; }
    public string OriginalQueue { get; set; }
    public string CurrentDepartment { get; set; }
    public string CurrentQueue { get; set; }
}

我想为这些类型创建复杂类型,如下所示:

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

我想使用相同类型的当前和原始:

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

这可能吗?还是我需要创建两个复杂类型CurrentLocationOriginalLocation

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

实体框架-重用复杂类型

它是开箱即用的,您不需要创建两个复杂的类型。

您还可以使用模型生成器显式地配置您的复杂类型

modelBuilder.ComplexType<Location>();

要自定义列名,您应该从父实体配置中配置它们

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");
    }
}

这将把MyEntity.Current.Queue映射到myCustomName