【发布时间】:2012-02-15 17:24:03
【问题描述】:
我对 Entity Framework 4 比较陌生。
我的项目由一个 WebApplication 和 ClassLibrary 项目组成。我不得不使用 ADO.Net POCO 实体生成器,因为我在 ClassLibrary 项目中有多个 edmx 文件,它们之间有某些通用模型。
在 edmx 中,我有用于 User、Role 和 UserRole 的表(仅包含 2 个外键列,UserID 和 RoleID)。实体框架创建了两个模型,即用户和角色,分别具有角色和用户的导航属性。我已从 .edmx 中删除了 definedQuery,这使我能够将记录添加到 UserRole 表中。
在我的网络表单中,我有以下代码:
插入角色:
User user = new User(iUserID); //initializes the the user object with the user info
user.AddRole(RoleID); //passes in the roleid that needs to be inserted`
删除用户角色:
User user = new User(iUserID); //initializes the the user object with the user info
user.RemoveRole(RoleID); //passes in the roleid that needs to be deleted`
部分用户类的内容(构造函数和2个方法):
public User(short UserID)
{
using (SecurityEntities Context = new SecurityEntities())
{
User user = Context.Users.Where(ua => ua.UserID == UserID).Single<User>();
this.UserID = user.UserID;
// etc...
}
}
public void AddRole(short roleID)
{
using (SecurityEntities Context = new SecurityEntities())
{
Role role = Context.Roles.Where(r => r.RoleID == roleID).Single<Role>();
Context.AttachTo("Users", this);
this.Roles.Add(role);
Context.SaveChanges();
}
}
public void RemoveRole(short roleID)
{
using (SecurityEntities Context = new SecurityEntities())
{
Role role = Context.Roles.Where(r => r.RoleID == roleID).Single<Role>();
Context.AttachTo("Users", this);
this.Roles.Remove(role);
Context.SaveChanges();
}
}
我的问题是
- 在 AddRole 方法中,如果我不使用 AttachTo(),则会将当前用户的重复记录输入到 User 表中,并将角色插入到 UserRole 中。为什么 attachTo() 会阻止这种情况发生?
- 在RemoveRole方法中,代码运行流畅,没有错误,但表中的记录没有被删除。为什么?
谁能帮帮我?
【问题讨论】:
标签: entity-framework entity-framework-4