简体   繁体   English

一个与HasForeignKey为零或一

[英]One to zero-or-one with HasForeignKey

I have two models: 我有两个型号:

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");
    }
}

I want to map them using fluent mapping. 我想使用流畅的映射来映射它们。 Employee table has column 'person_id' which is non-nullable. Employee表的列'person_id'是不可为空的。 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 : One or more validation errors were detected during model generation: System.Data.Entity.ModelConfiguration.ModelValidationException:在模型生成期间检测到一个或多个验证错误:

person_id: Name: Each property name in a type must be unique. person_id:名称:类型中的每个属性名称必须是唯一的。 Property name 'person_id' is already defined. 已定义属性名称“person_id”。

I need PersonId property on its own, so what I basically want is: 我自己需要PersonId属性,所以我基本上想要的是:

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

But there is no such method here as HasForeignKey 但是这里没有 HasForeignKey 这样的方法

OK, I figured that out - you should use WithMany (yep, not obvious) in order to store foreign key in some property: 好吧,我想出来 - 你应该使用WithMany (是的,不明显),以便将外键存储在某些属性中:

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

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. BTW这将为人员表创建员工外键列,但没有其他方法可以分别拥有导航属性和外键。


If you need foreign key read-only, you can change PersonId property to: 如果需要外键只读,可以将PersonId属性更改为:

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

And use your original mapping 并使用您的原始映射

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

There's actually a better way to do this: 实际上有更好的方法:

HasKey(e => e.PersonId);

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

Note that you no longer need the Employee.Id property with this approach, as it was superfluous in terms of a 1 to 0 or 1 relationship in the first place. 请注意,您不再需要使用此方法的Employee.Id属性,因为它首先在1到0或1关系方面是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM