一个实体多个引用的情况
我们来考虑一下下面的情况:
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 Person16 {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 使用遇到的一些问题
关键词: