Come aggiungere / rimuovere molti-a-molti relazione con Entity Framework da chiave di entità?
-
21-08-2019 - |
Domanda
ho provato:
using (Entities e = new Entities())
{
EntityKey key = new EntityKey("Entities.Users", "UserId", 20);
User user = new User { EntityKey = key};
Role role = e.Roles.FirstOrDefault();
//role.Users.Attach(user); //throws (when uncommented...) InvalidOperationException:
//The object being attached to the source object is not attached to the same ObjectContext as the source object.
role.Users.Add(user); //throws InvalidOperationException too:
//The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
e.SaveChanges();
}
Quando si tenta di utilizzare Remove () senza chiamare allegare prima non viene generata un'eccezione, ma non eliminato relazione.
Soluzione
Provare qualcosa di simile a questo:
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
Trovo molto più facile lavorare con Enti stub (come l'utente di cui sopra), piuttosto che EntityKeys.
Vedere questo post sul blog per più informazioni tecniche Stub entità.
Spero che questo aiuti
Alex
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow