Entity Framework实体到表的高级映射

1. 映射表名和列明

[Table("People")]
public class PersonPhoto {
…    
    [Column("CaptionName")]
    public string Caption { get; set; }
…  
}
如果还需要指定schema名称:
[Table("Locations", Schema="baga")]
public class Destination{...}
 
Fluent API
ToTable("People", "tvl");
Property(t => t.Caption ).HasColumnName("CaptionName");







2. 多实体映射到单表

[Table("People")]
public class Person {
   ...
    [Required]
    public PersonPhoto Photo { get; set; }
}

[Table("People")]
public class PersonPhoto {
    [Key]
    [ForeignKey("PhotoOf")]
    public int PersonId { get; set; }
   ...
}

这里需要强调的是

1. 实体间一对一的关系;
2. 这里Person类里面的Photo字段必须使用Required修饰,否则无效;
3. 实体都使用显示的声明属性、配置来命名。(否则隐性将会导致其重复命名的表名后面加1,比如Person默认表名就是Person,如果没有显示声明表名为People,将会别改名为People1)

Lazy Load

如上类所示,想要加载Photo,需要通过context.People.Include("Photo")来加载。但是如果声明如下(使用virtual修饰):

[Required]
public virtual PersonPhoto Photo { get; set; }

则默认的行为是Lazy Load的方式,当通过

var people = context.People.ToList();
var firstPerson = people[0];
SomeCustomMethodToDisplay(firstPerson.Photo.Caption);
方式访问Photo将会实时的访问数据库取回Photo信息,如果不声明virtual,上例将会抛出异常。

Fluent API:

modelBuilder.Entity<Person>().ToTable("People");
modelBuilder.Entity<PersonPhoto>().ToTable("People");

3. 单实体映射到多表

 public class DestinationConfig : EntityTypeConfiguration<Destination> { 
     public DestinationConfig(){
         Map(m => {
             m.Properties(d => new { d.Name, d.Country,d.Description });
             m.ToTable("Locations");
         });
         Map(m => {
             m.Properties(d => new {d.Photo });
             m.ToTable("LocationPhotos");
         });
     }
 }

image

image

image

4. 如何实现实体到数据库表的映射

1. 在DbContext的继承类中,通过Dbset暴露出来;
2. 以着关联类的形式,在符合第一条的类中出现;
3. 以着Fluent API的形式在OnModelCreating方法中定义或者成为modelBuilder.Configurations中的添加类,如果这样的实体需要使用EntityTypeConfiguration定义一下。

原文地址:https://www.cnblogs.com/xiashiwendao/p/3006260.html