entity framework – 重用复杂类型

我在Code First Entity框架中有一个实体,目前看起来像这样:

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

我想在Current和Original中使用相同的类型:

 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(); 

要自定义列名称,应从父实体配置进行配置

 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(); modelBuilder.Entity().Property(x => x.Current.Queue).HasColumnName("myCustomColumnName"); } } 

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