【问题标题】:EntityObject.Remove() does not delete record from databaseEntityObject.Remove() 不会从数据库中删除记录
【发布时间】: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();
    }
}

我的问题是

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

谁能帮帮我?

【问题讨论】:

    标签: entity-framework entity-framework-4


    【解决方案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);
    }
    

    重要的是使用属于单个上下文实例的实体。否则,您将不得不脱离先前的上下文并附加到当前上下文。

    【讨论】:

    • 亲爱的 Eranga,我无法将上下文对象传递给初始调用创建用户对象的网页函数。但是,正如您所建议的那样,我已将 Role 对象提供给 removeRole 方法并尝试了各种事情(分离/附加等),但记录根本不会被删除。你能解释一下我如何按照建议分离和附加角色对象吗?
    • @RaviShet 在最后两个示例中,SaveChanges 方法应该由RemoveRole 方法的调用者调用
    猜你喜欢
    • 2013-05-05
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 2016-10-16
    相关资源
    最近更新 更多