【问题标题】:EF Code First: Fluent API Configuration - How to configure properties of subclasses in TPH?EF Code First: Fluent API Configuration - 如何在 TPH 中配置子类的属性?
【发布时间】:2018-02-04 12:48:35
【问题描述】:

如果我在 TPH 配置中有一个基类和两个派生类,如何在 fluent API 中配置派生类的标量属性(例如字符串的长度)?

示例: 公共枚举 PersonType { Employee, Manager }

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

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您配置派生实体的方式与配置常规实体的方式相同 - 通过使用单独的流式配置,例如

    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);
            // ... 
        } 
    }
    

    【讨论】:

    • 嗨伊万斯托耶夫!感谢您及时的回复。你的建议似乎很完美。您能否确认为派生类创建单独的类型配置是否不会为这些类创建表。我期待 TPH 行为,即只有一个表具有派生类的鉴别器字段。谢谢。
    • 当然。 仅如果您通过用于设置 TPT 的ToTable 明确请求,它将创建单独的表。
    猜你喜欢
    • 1970-01-01
    • 2013-10-21
    • 2013-02-14
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多