问题描述
我有两个型号:
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<Employee>
{
public EmployeeConfiguration()
{
Property(e=>e.PersonId) // I need this property mapped
.HasColumnName("person_id")
.HasColumnType("int");
}
}
我想用流利的映射映射。 Employee表中有PERSON_ID列是不可为空。我尝试以下操作:
I want to map them using fluent mapping. Employee table has column 'person_id' which is non-nullable. I tried following:
HasRequired(e => e.Person)
.WithOptional(p => p.Employee)
.Map(m => m.MapKey("person_id"));
但它失败:
But it fails with:
System.Data.Entity.ModelConfiguration.ModelValidationException:模型生成过程中检测到一个
或多个验证错误:
为person_id:名称:在类型每个属性名称必须是唯一的。物业
名称'PERSON_ID'已定义。
person_id: Name: Each property name in a type must be unique. Property name 'person_id' is already defined.
我需要自己的PERSONID的财产,所以我基本上要为
I need PersonId property on its own, so what I basically want is:
HasRequired(e => e.Person)
.WithOptional(p => p.Employee)
.HasForeignKey(e => e.PersonId); // there is no such method
但有没有这样的方法点击这里作为HasForeignKey
But there is no such method here as HasForeignKey
推荐答案
好吧,我想通了这一点 - 你应该使用 WithMany
(是的,不明显)为了存储在某些属性外键:
OK, I figured that out - you should use WithMany
(yep, not obvious) in order to store foreign key in some property:
Property(e => e.PersonId).HasColumnName("person_id");
HasRequired(e => e.Person)
.WithMany()
.HasForeignKey(p => p.PersonId);
请参阅的文章详细信息。顺便说一句,这将创建一个人的EMPLOYEE表的外键列,但没有其他的办法有导航属性和单独的外键。
See One-to-One Foreign Key Associations article for details. BTW this will create employee foreign key column for person's table, but there is no other way to have navigation property and foreign key separately.
如果你需要外键只读,你可以改变PERSONID属性:
If you need foreign key read-only, you can change PersonId property to:
public int PersonId { get { return Person.Id; } }
和使用原来的映射
HasRequired(e => e.Person)
.WithOptional(p => p.Employee)
.Map(m => m.MapKey("person_id"));
这篇关于一至零或酮与HasForeignKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!