EntityObject.Remove()不会从数据库中删除记录

时间:2012-02-15 07:36:21

标签: entity-framework entity-framework-4

我对Entity Framework 4相对较新。

我的项目包括WebApplication& ClassLibrary项目。我不得不使用ADO.Net POCO实体生成器,因为我在ClassLibrary项目中有多个edmx文件,其中包含某些常见模型。

在edmx中我有User,Role& amp; UserRole(仅包含2个外键列,UserID& RoleID)。实体框架分别创建了两个模型,即用户和角色,分别具有角色和用户的导航属性。我已经从.edmx中删除了defineQuery,这使我能够将记录添加到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();
    }
}

我的问题是

  1. 在AddRole方法中,如果我不使用AttachTo(),则会在User表中输入当前用户的重复记录,并将角色插入到UserRole中。为什么attachTo()会阻止这种情况发生?
  2. 在RemoveRole方法中,代码运行顺畅,没有错误,但表中的记录不会被删除。为什么?
  3. 有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

在这两种情况下,您都错误地使用了实体框架。用户由(然后跟踪)不同的上下文创建。然后使用不同的上下文实例检索角色。

将创建user的上下文实例提供给方法

public void AddRole(SecurityEntities Context, short roleID)
{
        Role role = Context.Roles.Where(r => r.RoleID == roleID).Single<Role>();

        this.Roles.Add(role);
        Context.SaveChanges();
}

或将Role实例提供给方法

public void AddRole(Role role)
{
        this.Roles.Add(role);
}

删除方法也遭遇类似问题

public void RemoveRole(short roleID)
{
     var role = this.Roles.Where(r => r.RoleID == roleID).Single();
     this.Roles.Remove(role);
}

重要的是使用属于单个上下文实例的实体。否则,您必须从先前的上下文中分离并附加到当前上下文。

相关问题