I have two classes with a M:N Relation. For Example:
class User
{
int Id
string Name
ICollection<Addresses> Adresses
}
class Address
{
int Id
string Text
ICollection<User> Users
}
Everything went fine so far. EF created automatically a N:M
table in my database. UserAddress
with 2 columns (UserId
and AddressId
).
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<Address> 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 don't want him to add a new address. I want him to take the existing address from the db.