Entity framework EF代码优先:Fluent API配置-如何在TPH中配置子类的属性?
如果在TPH配置中有一个基类和两个派生类,如何在fluent API中配置派生类的标量属性(例如字符串长度) 例如: public enum PersonType{Employee,Manager}Entity framework EF代码优先:Fluent API配置-如何在TPH中配置子类的属性?,entity-framework,Entity Framework,如果在TPH配置中有一个基类和两个派生类,如何在fluent API中配置派生类的标量属性(例如字符串长度) 例如: public enum PersonType{Employee,Manager} public abstract class Person { public string FirstName {get; set;} public string LastName {get; set;} } public class Employee : Person
public abstract class Person
{
public string FirstName {get; set;}
public string LastName {get; set;}
}
public class Employee : Person
{
public string Designation {get; set;}
}
public class Manager : Person
{
public string Division {get; set;}
}
//fluent api config
internal class PersonConfig : EntityTypeConfiguration<Person>
{
public PersonConfig()
{
Property(p => p.FirstName) .HasMaxLength(250);
Property(p => p.LastName) .HasMaxLength(250);
Map<Employee>(e => e.Requires(x => x.PersonType).HasValue());
**//how to configure Designation ?**
Map<Manager>(m => m.Requires(y => y.PersonType).HasValue());
**//how to configure Division ?**
}
}
公共抽象类人物
{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
}
公共类员工:人
{
公共字符串名称{get;set;}
}
公共类经理:个人
{
公共字符串除法{get;set;}
}
//fluent api配置
内部类PersonConfig:EntityTypeConfiguration
{
公共人员配置()
{
属性(p=>p.FirstName).HasMaxLength(250);
属性(p=>p.LastName).HasMaxLength(250);
Map(e=>e.Requires(x=>x.PersonType.HasValue());
**//如何配置指定?**
Map(m=>m.Requires(y=>y.PersonType).HasValue());
**//如何配置部门?**
}
}
您可以像配置常规实体一样配置派生实体-使用单独的fluent配置,例如
internal class EmployeeConfig : EntityTypeConfiguration<Employee>
{
public EmployeeConfig()
{
Property(e => e.Designation).HasMaxLength(250);
// ...
}
}
internal class ManagerConfig : EntityTypeConfiguration<Manager>
{
public ManagerConfig()
{
Property(m => m.Division).HasMaxLength(250);
// ...
}
}
内部类EmployeeConfig:EntityTypeConfiguration
{
公共雇员配置()
{
属性(e=>e.名称)。HasMaxLength(250);
// ...
}
}
内部类管理器配置:EntityTypeConfiguration
{
公共管理器配置()
{
属性(m=>m.Division).HasMaxLength(250);
// ...
}
}
你好,伊万·斯托夫!谢谢你的快速回复。你的建议似乎很完美。请确认为派生类创建单独的类型配置是否不会为这些类创建表。我期望TPH行为,即只有一个表具有派生类的鉴别器字段。谢谢,当然。仅当您通过用于设置TPT的ToTable
明确请求时,它才会创建单独的表。