开发者

Unable to save many-to-many relationship

I have the following tables/views

Users (View)
-> UserId
-> Name

Roles (Table)
-> RoleId
-> Name

UserRoles (Table)
-> UserId
-> RoleId

and the classes

public class Role{
     public int RoleId{get;set}
     public string Name{get;set}
}

public class User{
     public int UserId{get;set}
     public string Name{get;set}
     public ICollection<Role> Roles{get;set}
}

and the save method

using (var helper = new DbContext())
{
     helper.Users.Attach(user);
     helper.SaveChanges();
}

As you can see above, the Users is a view and UserRoles is a mapping table. I am able to retrieve User entities along with the mapped Roles. But while saving it is not throwing any exceptions nor is it saving. I tried checking th开发者_如何学运维e db using profiler and it is not even hitting the db.

Since Users is a view I don't want to save the User entity but only the changes made in the Roles collection.


This cannot save anything. Attach puts the whole object graph into the context, but in state Unchanged. If all objects in the context are unchanged SaveChanges won't issue any command to the DB (because for EF nothing has changed).

If you want to make changes which EF recognizes as such you must first attach the object which represents the state in the Db and then make your changes, something like:

using (var helper = new DbContext())
{
    helper.Users.Attach(user);
    helper.Roles.Attach(myNewRole);
    user.Name = myNewName;
    user.Roles.Add(myNewRole);
    // etc.
    helper.SaveChanges();
}

Alternatively you can mark the user as modified:

helper.Entry(user).State = EntityState.Modified;

But I believe this only affects scalar properties of the entity and it doesn't solve the problem to add a new role to the user.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜