使用 Fluent API 配置/映射属性和类型2

1.将多个实体类映射到数据库中的一个表

   要将多个实体映射到一个数据库表需要满足:

   a. 两个实体必须是一对一关系

   b.两个实体共享一个主键

 1  public  class MyContext:DbContext
 2     {
 3         public MyContext()
 4             : base("test")
 5         { }
 6         protected override void OnModelCreating(DbModelBuilder modelBuilder)
 7         {
 8             modelBuilder.Entity<Person>()
 9                 .HasRequired(p => p.Detail)
10                 .WithRequiredPrincipal();
11         }
12         public DbSet<Person> Persons { get; set; }
13         public DbSet<PersonDetail> PersonDetails { get; set; }
14 
15     }
16 
17     [Table("Person")]
18     public class Person
19     {
20         public int Id { get; set; }
21         public string Name { get; set; }
22         public bool Sex { get; set; }
23         public PersonDetail Detail { get; set; }
24     }
25     [Table("Person")]
26     public class PersonDetail
27     {
28         [Key,ForeignKey("Person")]
29         public int Id { get; set; }
30         public DateTime Birth { get; set; }
31         public byte[] Photo { get; set; }
32         public Person Person { get; set; }
33     }
34 }
View Code

 

2.将实体类型的 CLR 属性映射到数据库中的多个表

 1  public  class MyContext:DbContext
 2     {
 3         public MyContext()
 4             : base("test")
 5         { }
 6         protected override void OnModelCreating(DbModelBuilder modelBuilder)
 7         {
 8             modelBuilder.Entity<Person>()
 9                 .Map(p =>
10                 {
11                     p.Properties(t => new { t.Id, t.Name, t.Sex });
12                     p.ToTable("Person");
13                 })
14                 .Map(p =>
15                 {
16                     p.Properties(t => new { t.Birth, t.Photo });
17                     p.ToTable("PersonDetails2");
18                 }
19                 );
20         }
21         public DbSet<Person> Persons { get; set; } 
22     }
23 
24     [Table("Person")]
25     public class Person
26     {
27         public int Id { get; set; }
28         public string Name { get; set; }
29         public bool Sex { get; set; }  
30         public DateTime Birth { get; set; }
31         public byte[] Photo { get; set; }
32     }
View Code

 

转载于:https://www.cnblogs.com/goodlucklzq/p/4612060.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值