简体   繁体   English

实体框架-代码优先关系映射

[英]Entity Framework - Code first relationship mapping

I have a situation whereby I EntityA should have an property named "PropertyB" that points to an optional instance of EntityB, and EntityB has a property called PropertyA that points back to an EntityA instance - though NOT necessarily the same instance of entityA that we started with... 我遇到一种情况,我的EntityA应该具有一个名为“ PropertyB”的属性,该属性指向EntityB的一个可选实例,而EntityB的一个名为PropertyA的属性则指向一个EntityA实例-尽管不一定与我们启动的相同。与...

Any idea how to handle this in code first? 知道如何先在代码中处理这个吗?

The exact scenario I am looking at involves OrganisationMembers and Orgainsations. 我正在查看的确切场景涉及OrganisationMembers和Orgainsations。 OrganisationMembers are of course members of an organisation, which I model through having a property on the OrganisationMember pointing to the Organisation. 当然,OrganisationMembers是组织的成员,我通过在OrganisationMember上拥有指向该组织的属性来建模。

At the same time, Organisations have nominated person as a point of contact (or POC), which is modelled as a property of type OrganisationMember. 同时,组织已指定人作为联系点(或POC),其建模为OrganisationMember类型的属性。

When I try and create a migration for this, I get told that EF can't determine which is the principal and which is the dependent. 当我尝试为此创建迁移时,我被告知EF无法确定哪个是主体,哪个是从属。

Ideas anyone? 有任何想法吗?

Your EntityA , EntityB relation can be achieved like this: 您的EntityAEntityB关系可以这样实现:

public class EntityA
{
    public int Id { get; set; }

    public virtual EntityB EntityB { get; set; }
}

public class EntityB
{
    public int Id { get; set; }

    public virtual EntityA EntityA { get; set; }
}

And you need to tell Entity Framework about the relation: 并且您需要告诉实体框架有关该关系的信息:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityA>()
        .HasOptional(x => x.EntityB)
        .WithOptionalDependent();

    modelBuilder.Entity<EntityB>()
        .HasOptional(x => x.EntityA)
        .WithOptionalDependent();
}

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

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