码迷,mamicode.com
首页 > 其他好文 > 详细

EF Code First 学习笔记,关于特性InverseProperty 使用遇到的一些问题

时间:2016-01-13 00:36:37      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:

一个实体多个引用的情况

我们来考虑一下下面的情况:

技术分享
 1 public class Lodging
 2     {
 3         public int LodgingId { get; set; }
 4         public string Name { get; set; }
 5         public string Owner { get; set; }
 6         public bool IsResort { get; set; }
 7         public decimal MilesFromNearestAirport { get; set; } 
 8         public Destination Target { get; set; }
 9         //第一联系人
10         public Person PrimaryContact { get; set; }
11         //第二联系人
12         public Person SecondaryContact { get; set; } 
13     } 
14 
15     public class Person
16     {
17         public int PersonID { get; set; }
18         public string FirstName { get; set; }
19         public string LastName { get; set; }
20         public List<Lodging> PrimaryContactFor { get; set; }
21         public List<Lodging> SecondaryContactFor { get; set; } 
22     }
View Code

Lodging(旅店)有两个对Person表的引用,分别是PrimaryContact与SecondaryContact,同时,在Person表中也有对这两个联系人的导航:PrimaryContactFor与SecondaryContactFor。

看看Code First默认会生成怎样的数据库

Lodging(旅店)有两个对Person表的引用,分别是PrimaryContact与SecondaryContact,同时,在Person表中也有对这两个联系人的导航:PrimaryContactFor与SecondaryContactFor。

看看Code First默认会生成怎样的数据库

技术分享

天哪,竟然生成了四个外键。因为有两套类型一样的导航属性与引用属性,Code First无法确定它们之间的对应关系,就单独为每个属性都创建了一个关系。这肯定不是我们所期望的,为了让Code First知道它们之间的对应关系,在这里要用到逆导航属性来解决。

使用Data Annotations:但是!!!!!,我用下面的第一种方法,未成功,具体原因不明,希望有知道的可以给我一些指点,最终用的第二种方法来时间的关系

技术分享
1        //第一联系人
2         [InverseProperty("PrimaryContactFor")] 
3         public Person PrimaryContact { get; set; }
4         //第二联系人
5         [InverseProperty("SecondaryContactFor")] 
6         public Person SecondaryContact { get; set; } 
View Code

或使用Fluent API:

技术分享
1  modelBuilder.Entity<Lodging>().HasOptional(l => l.PrimaryContact).WithMany(p => p.PrimaryContactFor);
2  modelBuilder.Entity<Lodging>().HasOptional(l=>l.SecondaryContact).WithMany(p=>p.SecondaryContactFor);
View Code

 

再重新生成数据库,结果如图:

技术分享

EF Code First 学习笔记,关于特性InverseProperty 使用遇到的一些问题

标签:

原文地址:http://www.cnblogs.com/prpr/p/5126017.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!