Как добавить/удалить связь «многие ко многим» с инфраструктурой сущности по ключу сущности?
-
21-08-2019 - |
Вопрос
Я пытался:
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();
}
При попытке использовать Remove() без вызова Attach до исключения не создается, но отношение не удаляется.
Решение
Попробуйте что-то вроде этого:
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
Мне гораздо проще работать с заглушками (например, с пользователем выше), чем с EntityKeys.
Видеть это Сообщение блога для получения дополнительной информации о методах Stub Entity.
Надеюсь это поможет
Алекс
Не связан с StackOverflow