Skip to content

Instantly share code, notes, and snippets.

@JansthcirlU
Last active October 21, 2021 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JansthcirlU/fe95b15e7cd200e707853d0b6c4528ff to your computer and use it in GitHub Desktop.
Save JansthcirlU/fe95b15e7cd200e707853d0b6c4528ff to your computer and use it in GitHub Desktop.
Link table with the names of the linked entities
public class ABDbContext : DbContext
{
public DbSet<ClassA> ClassAs { get; set; }
public DbSet<ClassB> ClassBs { get; set; }
public DbSet<ABLink> ABLinks { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Custom many-to-many, see: https://dev.to/shibayan/tried-entity-framework-core-5-0-s-many-to-many-support-4och
modelBuilder
.Entity<ClassA>()
.HasMany(a => a.ClassBs)
.WithMany(b => b.ClassAs)
.UsingEntity<ABLink>
(
link => link.HasOne(l => l.ClassA).WithMany(),
link => link.HasOne(l => l.ClassB).WithMany()
)
.HasKey(link => link.LinkId);
}
/* ... */
}
public class ClassA
{
public int AId { get; set; }
public string AName { get; set; }
// Many to many
public List<ClassB> ClassBs { get; set; }
}
public class ClassB
{
public int BId { get; set; }
public string BName { get; set; }
// Many to many
public List<ClassA> ClassAs { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment