Search code examples
c#entity-frameworkpartial-classes

EF Many to many relationship with additional properties


I know that this is a repeated question and I know that this is not possible if there are additional properties in the "in the middle" table.

I had an idea how to get the effect of an m:N relationship instead of an 1:n-n-1, but I'd like to hear some other thoughts.

If I have three entities, A, B, and AB where AB makes the A:B relation possible and it has additional properties.

Using Databasefirst approach, I thought to make a partial class of A and B.

public partial Class A
{
    public IEnumerable<EntityObject> Bs 
    {
        get
        {
            return this.Select(p=>p.AB.B);
        }
        set { //... }
    }
}

Could something like this be possible.

Just doodling in my head. I am currently on vacation and have no computer, so this is not tested but just written on my cell phone.

I see that this could be a problem after context disposing or detaching, also with including in an eager loading approach.

Any thoughts?


Solution

  • If you are already treating AB as a distinct entity, then to get all B from A all you need is something like this:

    public partial class A
    {
        public IQueryable<B> Bs {
            get { return this.ABs.AsQueryable().Select(ab => ab.B).Distinct(); }
        }
    }
    

    I'm not sure how well this will perform, as compared to a built-in Many-To-Many supported by EF (without any payload), but it will give you what you are asking.