Entity Framework实体到表的高级映射(二)

1. 属性不映射到数据库表字段

public class Destination {
    …    
    [NotMapped]
    public DateTime CreateOn { get; set; }
}
或者只定义getter方法
public string FullName
{
    get { return String.Format("{0} {1}",FirstName.Trim(), LastName); }
}
 
Fluent API:
Ignore(d => d.CreateOn);

2. 映射继承关系

2.1 Table Per Hierarchy(TPH) 基类和子类映射到同一张表,TPH也是EF默认的处理方式,不需要添加任何属性声明。除了会向基类所在的表中添加子类增加的字段外,还会添加一个“Discriminator“字段,内容为类名,用于区别基类和子类。

2.2 Table Per Type(TPT) 基类和子类在不同的表,子类的表结构中只有增加的字段,取子表的信息需要通过和主表关联取得。

[Table("Restore")]
public class Restore: Destination {
    public string Entertainment { get; set; }
    public string Activities { get; set; }
}
image

Fluent API:

modelBuilder.Entity<Resort>().ToTable("Resorts");

2.3 Table Pre Concrete(TPC) 映射子类为单独的表,并且包含全部父类的定义的字段。只能通过Fluent API的方式指定:

.Map<Resort>(m =>
{
    m.ToTable("Resorts");
    m.MapInheritedProperties();
});
原文地址:https://www.cnblogs.com/xiashiwendao/p/3007564.html