dc7a9163d9 dc7a9163d9 - 29 days ago 19
C# Question

Many-to-many relationship on EF core 1.0 code first with model first?

I already have the following tables.

create table A (Id char(8) primary key, .....)
create table B (Id int primary key, .....)
create table A_B (AId references A(Id), BId references B(Id), primarykey(AId, BId))


What's the best way to define the class for these many-to-many relationship?

class A {
public string Id { get; set; }
....
public List<B> Bs { get; set; } or List<A_B> A_Bs?
}
class B {
public int Id { get; set; }
....
public List<A> As { get; set; } or List<A_B> A_Bs?
}
class A_B ???

Answer

EFCore doesn't support many-to-many without join table yet, so you must use something like:

class A {
      List<A_B> A_Bs {get;set;}
    }

    class A_B {
      int AId {get;set;}
      A MyA {get;set;}
      int BId {get;set;}
      B MyB {get;set;}
    }

class B {
    List<A_B> A_Bs {get;set;}
}
Comments