无法保存多对多关系
我有以下表/视图
Users (View)
-> UserId
-> Name
Roles (Table)
-> RoleId
-> Name
UserRoles (Table)
-> UserId
-> RoleId
以及类
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}
}
和保存方法
using (var helper = new DbContext())
{
helper.Users.Attach(user);
helper.SaveChanges();
}
正如您在上面看到的,Users 是一个视图,UserRoles 是一个映射表。我能够检索用户实体以及映射的角色。但是在保存时它不会抛出任何异常,也不会保存。我尝试使用探查器检查数据库,但它甚至没有命中数据库。
由于用户是一个视图,我不想保存用户实体,而只想保存在角色集合中所做的更改。
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 the 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这无法拯救任何东西。
Attach
将整个对象图放入上下文中,但处于状态Unchanged
。如果上下文中的所有对象均未更改,SaveChanges
将不会向数据库发出任何命令(因为对于 EF 而言,没有任何更改)。如果您想要进行 EF 识别的更改,您必须首先附加代表数据库中状态的对象,然后进行更改,例如:
或者您可以将用户标记为已修改:
但我相信这只会影响标量属性实体的角色,并不能解决向用户添加新角色的问题。
This cannot save anything.
Attach
puts the whole object graph into the context, but in stateUnchanged
. If all objects in the context are unchangedSaveChanges
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:
Alternatively you can mark the user as 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.