我想在用户中添加和编辑项目。我使用这段代码:
DataContext db = new DataContext();
private void Save()
{
User user = (SelectedUser == null) ? new User() : db.User.Find(SelectedUser.UserName);
user.FirstName = FirstName;
user.CcRowIndex = CcRowIndex;
user.Image = Image;
user.LastName = LastName;
user.OrganizationalPostId = OrganizationalPost;
user.OrganizationalUnitId = OrganizationalUnit;
user.Password = Password;
user.Signature = Signature;
user.SubsetUsers = SubsetUsersList;
user.UserName = UserName;
if (SelectedUser == null)
{
db.User.Add(user);
}
db.SaveChanges();
}
我添加了项目,但是当我编辑项目时,我收到错误:
无法定义两个对象之间的关系,因为它们附加到不同的ObjectContext对象。+ savechange of datacontext
答案 0 :(得分:1)
查看User
课程的定义会有所帮助,但我可以猜一猜。
假设:
SubsetUsersList
属性是其他User
个实例从SubsetUsersList
的另一个实例填充DbContext
。当您尝试在新DbContext
实例中使用这些实体时,EF会抱怨。
// SubsetUsersList populated by unknown DbContext instance
user.SubsetUsers = SubsetUsersList;
// db instance throws exception
db.SaveChanges();
另一种方法是在当前db
实例中加载这些用户:
// Guessing at the definition of your User class
var subsetUserIds = SubsetUsersList.Select(u => u.UserId).ToArray();
user.SubsetUsers = db.User.Where(u => subsetUserIds.Contains(u.UserId).ToList();
效率不高,但应该可以帮助您理解这个问题。