一个与HasForeignKey为零或一

我有两个型号:

public class Person { public virtual int Id { get; set; } public virtual Employee Employee { get; set; } // optional } public class Employee { public virtual int Id { get; set; } public virtual int PersonId { get; set; } public virtual Person Person {get; set; } // required } public class EmployeeConfiguration : EntityTypeConfiguration { public EmployeeConfiguration() { Property(e=>e.PersonId) // I need this property mapped .HasColumnName("person_id") .HasColumnType("int"); } } 

我想使用流畅的映射来映射它们。 Employee表具有不可为空的列’person_id’。 我试过以下:

 HasRequired(e => e.Person) .WithOptional(p => p.Employee) .Map(m => m.MapKey("person_id")); 

但它失败了:

System.Data.Entity.ModelConfiguration.ModelValidationException:在模型生成期间检测到一个或多个validation错误:

person_id:名称:类型中的每个属性名称必须是唯一的。 已定义属性名称“person_id”。

我自己需要PersonId属性,所以我基本上想要的是:

 HasRequired(e => e.Person) .WithOptional(p => p.Employee) .HasForeignKey(e => e.PersonId); // there is no such method 

但是这里没有 HasForeignKey 这样的方法

好吧,我想出来 – 你应该使用WithMany (是的,不明显),以便将外键存储在某些属性中:

 Property(e => e.PersonId).HasColumnName("person_id"); HasRequired(e => e.Person) .WithMany() .HasForeignKey(p => p.PersonId); 

有关详细信息,请参阅一对一外键关联文章。 BTW这将为人员表创建员工外键列,但没有其他方法可以分别拥有导航属性和外键。


如果需要外键只读,可以将PersonId属性更改为:

 public int PersonId { get { return Person.Id; } } 

并使用您的原始映射

 HasRequired(e => e.Person) .WithOptional(p => p.Employee) .Map(m => m.MapKey("person_id")); 

实际上有更好的方法:

 HasKey(e => e.PersonId); HasRequired(e => e.Person) .WithOptional(p => p.Employee); 

请注意,您不再需要使用此方法的Employee.Id属性,因为它首先在1到0或1关系方面是多余的。