I tried:
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();
我发现使用存根实体(如上面的用户)比使用 EntityKey 更容易。
看到这个博客文章 http://blogs.msdn.com/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx有关存根实体技术的更多信息。
希望这可以帮助
Alex
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)