简体   繁体   中英

The relationship between the two objects cannot be defined

I want add and edit items in Users. I use this code:

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();
}

I add Items, but when I edit items I get error:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.+ savechange of datacontext

It would help to see the definition of your User class, however, I can take a guess.

Assumption:

  • The SubsetUsersList property is a collection of other User instances

The SubsetUsersList is populated from another instance of your DbContext . When you attempt to use these entities in the new instance of DbContext , EF complains.

// SubsetUsersList populated by unknown DbContext instance
user.SubsetUsers = SubsetUsersList;

// db instance throws exception
db.SaveChanges();

An alternative is to load these users in the current db instance:

// 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();

This is not efficient, but should help you understand the issue here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM