ar.gorgin
ar.gorgin

Reputation: 5002

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

Upvotes: 2

Views: 605

Answers (1)

Ed Chapel
Ed Chapel

Reputation: 6932

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.

Upvotes: 1

Related Questions