【发布时间】:2009-07-03 02:28:46
【问题描述】:
我试过了:
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 在没有抛出异常但没有删除关系之前。
【问题讨论】:
-
在您的 System.Data.Entity.DbContext 类型示例中是“实体”吗?
-
后研究:如果使用“AttachTo”,那么“Entities”必须是 ObjectContext。
-
LOL 可能,这是一个旧帖子...添加标签
标签: c# entity-framework many-to-many entity-relationship objectcontext