C
C#10mo ago
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!
4 Replies
Angius
Angius10mo ago
EF's support of hashsets is meh at best
Myridor
MyridorOP10mo ago
So i should ignore them and fill all tables by myself?
Angius
Angius10mo ago
The issue probably stems from the fact, that you create a duplicate entry on the join table I'd just use
public class A
{
public string Id { get; set; }
public string SecondId { get; set; }
public List<B> Bs { get; set; } = [];
}

public class B
{
public string Id { get; set; }
public List<A> As { get; set; } = [];
}
public class A
{
public string Id { get; set; }
public string SecondId { get; set; }
public List<B> Bs { get; set; } = [];
}

public class B
{
public string Id { get; set; }
public List<A> As { get; set; } = [];
}
Also, not sure if your code is actually the code you use, but your navigation properties weren't properties So that would be an issue for EF as well
Unknown User
Unknown User10mo ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server