"using both many-to-many and one-to-many to same entity" Code Answer

4

if you have more than one navigation property refering to the same entity ef does not know where the inverse navigation property on the other entity belongs to. in your example: does a.objectsofb refer to b.objecta or to b.otherobjectsofa? both would be possible and a valid model.

now, ef does not throw an exception like "cannot determine relationships unambiguously" or something. instead it decides that b.objecta refers to a third endpoint in b which is not exposed as navigation property in the model. this creates the first foreign key in table b. the two navigation properties in b refer to two endpoints in a which are also not exposed in the model: b.objecta creats the second foreign key in table b and b.otherobjectsofa creates a foreign key in table a.

to fix this you must specify the relationships explicitely.

option one (the easiest way) is to use the inverseproperty attribute:

public class a
{
    public int id { get; set; }
    public string name { get; set; }
    [inverseproperty("otherobjectsofa")]
    public virtual icollection<b> objectsofb { get; set; }
}

this defines that a.objectsofb is part of a many-to-many relation to b.otherobjectsofa.

the other option is to define the relationships completely in fluent api:

protected override void onmodelcreating(dbmodelbuilder modelbuilder)
{
    modelbuilder.entity<a>()
        .hasmany(a => a.objectsofb)
        .withmany(b => b.otherobjectsofa)
        .map(x =>
        {
            x.mapleftkey("aid");
            x.maprightkey("bid");
            x.totable("abs");
        });

    modelbuilder.entity<b>()
        .hasrequired(b => b.objecta)  // or hasoptional
        .withmany()
        .willcascadeondelete(false);  // not sure if necessary, you can try it
                                      // without if you want cascading delete
}
By Axbor Axrorov on June 21 2022

Answers related to “using both many-to-many and one-to-many to same entity”

Only authorized users can answer the Search term. Please sign in first, or register a free account.