문제

나는 시도했다 :

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 ()를 사용하려고 할 때 예외는 예외가 발생하지 않지만 관계는 삭제되지 않습니다.

도움이 되었습니까?

해결책

다음과 같은 것을 시도하십시오.

User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();

EntityKey가 아닌 위의 사용자와 같은 스텁 엔티티 (위의 사용자와 같은)와 함께 작업하는 것이 훨씬 쉽다는 것을 알게되었습니다.

이것 좀 봐 블로그 게시물 스터브 엔티티 기술에 대한 자세한 정보.

도움이 되었기를 바랍니다

알렉스

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top