Entity Framework 0..1 to 0 relation

ε祈祈猫儿з 提交于 2019-11-29 07:52:31

One-to-one relation is possible only if foreign key is also primary key of dependent entity. So the correct mapping is:

class First
{
    [Key]
    public int Id { get; set; }
}

class Second
{
    [Key, ForeignKey("First")]
    public int Id { get; set; }
    public First First { get; set; }
}

The reason is that to enforce one-to-one relation in the database foreign key must be unique in the Second entity. But entity framework doesn't support unique keys - the only unique value for EF is primary key. This is limitation of EF.

There is workaround described on Morteza Manavi's blog. Workaround is based on mapping association as one-to-many and enforcing uniqueness in database by introducing unique constraints in custom database initializer.

If you're trying to achieve a 1-to-1 relationship, where there is at the most only one Second entity associated to a First entity, and where there is no reverse property try the following:

class First
{
    [Key]
    public Guid FirstId { get; set; }
}

class Second
{
    [Key]
    public Guid FirstId { get; set; }
    public First First { get; set; }
}

class SecondMapping : EntityTypeConfiguration<Second>
{
    public SecondMapping()
    {
        this.HasRequired(s => s.First);
    }
}

You can however use a separate First_id column to do this kind of association, but then you would be effectively creating a 1-to-N relationship. It can be 'forced' to be 1-to-1 via a UNIQUE constraint, but you won't be able to create a reverse property due to a limitation in EF (as Ladislav mentioned):

class SecondMapping : EntityTypeConfiguration<Second>
{
    public SecondMapping()
    {
        this.HasRequired(s => s.First).WithMany().HasForeignKey("First_id");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!