I have two classes with a M:N Relation. For Example:
class User { int Id string Name
ICollection Adresses }
class Address { int Id string Text
ICollection Users }
Everything went fine so far. EF created automatically a N:M table in my database. UserAdress with 2 columns (UserId and AdressId).
When i insert data manually with SQL - the output of EF Core is fine. i get all my data. but now i have a problem with inserting from my app:
i create a new User and want to add an existing address. List ListOfAdresses (from DB)! var y = ListOfAdresses.First();
var x = new User(); x.Addresses.Add(y);
and now when i want to add this to the DBContext and save i get an error. He tries to create a new address... i get the error Duplicate Key Error. How can i prevent this? i dont want him to add a new address. i want him to take the existing address from the db.
CodePudding user response:
Maybe, u need to check your entity relations. I think, u can try to use x.AddressesId instead of x.Addresses.Add(y).
CodePudding user response:
You are missing a table to define the connection between the address and the user. You need a third table UserAddress { int Id int UserId int AddressId }
Your tables should look like following for a many to many
User { int Id ICollection Address - this is a virtual property }
these records should be unique otherwise you are storing duplicates
UserAddress {
int UserId - the id of the user
int AddressId - the address you are connecting them too
}
Address { int Id string Text }
When you call the save it should first persist the address then it will take the id of the newly stored address and the id of the user and save the link to the UserAddress table.
