© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
7 replies
Myridor

✅ EF Core 8.0.3 Many To Many Relation

quick question, im using entity framework core(8.0.3) code first approach:
I have 2 classes (many to many relation):
[PrimaryKey(nameof(Id), nameof(SecondId))]
public class A
{
  public string Id { get; set; }
  public string SecondId { get; set; }

  public virtual ICollection<B> Bs;

  public A()
  {
    Bs = new HashSet<B>();
  }
}
[PrimaryKey(nameof(Id), nameof(SecondId))]
public class A
{
  public string Id { get; set; }
  public string SecondId { get; set; }

  public virtual ICollection<B> Bs;

  public A()
  {
    Bs = new HashSet<B>();
  }
}


public class B
{
  [Key]
  public string Id { get; set; }

  public virtual ICollection<A> As;

  public B()
  {
    As = new HashSet<A>();
  }
}
public class B
{
  [Key]
  public string Id { get; set; }

  public virtual ICollection<A> As;

  public B()
  {
    As = new HashSet<A>();
  }
}

It's automatically creating the "third" table and on first entry its filling it aswell.


Now the first time I add some new stuff it works fine.
If I get the same Identifier tho it crashes, is there a way to automatically resolve it? or do I have to check if existing then add into table otherwise add to list?
b.As.Add(new A());
b.As.Add(new A());



Thanks in advance!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

EF Core many-to-many relation error
C#CC# / help
4y ago
[EF Core 8] Many-to-many relationship with payload
C#CC# / help
3y ago
EF Core Many to Many relationship through Entity
C#CC# / help
14mo ago
❔ EF Core duplicating many-to-many?
C#CC# / help
4y ago