0

i have this scenario when creating a new record it also recreates it's association.

User newUser = new User();
newUser.UserGroupID = 1;
newUser.UserGroup = UserGroup.Find(1);

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    context.Users.Add(newUser);
    context.SaveChanges();
}

when i save it, it creates a new User record, and so is a new UserGroup record.

4

3 回答 3

1

您正在为 UserGroup.Find() 和 Users.Add() 使用不同的上下文,这是不行的 - 对两者使用相同的上下文,它会正常工作。

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    var newUser = new context.Users.CreateNew();
    newUser.UserGroup = context.UserGroup.Find(1);

    context.Users.Add(newUser);
    context.SaveChanges();
}
于 2013-07-04T14:43:29.273 回答
0

您需要告诉上下文您的实体是现有实体:

User newUser = new User();
newUser.UserGroupID = 1;
newUser.UserGroup = UserGroup.Find(1);

using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
    context.UserGroups.Attach(newUser.UserGroup);
    context.Users.Add(newUser);
    context.SaveChanges();
}
于 2013-07-04T14:56:01.303 回答
0

这与此问题中的问题相同。对 Find 和 SaveChanges 使用相同的上下文,或者,如果由于某种原因无法完成,请使用 Attach() 将找到的 UserGroup 附加到新上下文。

于 2013-07-04T15:00:03.137 回答