代码之家  ›  专栏  ›  技术社区  ›  Dia Sheikh

在WinForms中使用EF6更新导航属性的非id字段

  •  2
  • Dia Sheikh  · 技术社区  · 7 年前

    当用户在表单上修改对象时,我想更新对象导航属性的非id字段。我的“Department”表的一些字段如下所示。。。

    Id
    DirectorId (object of Employee table)
    NoOfEmployees
    Location
    

    和Employee表的字段如下所示:

    Id
    Name
    Post
    

    现在,当用户看到部门表的修改时,我还会显示员工的核心信息(职位为“主管”),在其组合框中选择当前主管,并在相应的文本框中显示所有相关信息等。一旦用户选择了不同的主管,相关字段也会相应更改。

    现在我想要的是,如果用户此时更改了某些主管信息(例如姓名或年龄),这些更改应该反映在DB中,而不是强迫用户转到员工修改表并在那里进行更改。

    我尝试了修改数据库对象的几个字段的简单方法,但当要修改的对象是导航属性(如上所述)时,这种方法不起作用。这是代码。。。

    using (CompanyDBContext db = new CompanyDBContext() {
        int id = ((Department)cbDept.SelectedItem).Id;
        Department currentDept = db.Departments.Where(x => x.Id == id).First();
    
        Department newDept = new Department();
        newDept.Id = currentDept.Id;
        newDept.Employee.Id = (int)cbDir.SelectedValue; // --> has no effect;
        // raises NullRefException "Obj. ref. not set to an instance of an obj."
        .....;
        .....;
        db.Entry(currentDept).CurrentValues.SetValues(newDept);
    
        if (dirNameChanged) {
            var director = new Employee() {
                Id = currentDept.DirectorId,
                Name = tbDirName.Text.Trim()
            };
            db.Employees.Attach(director); // --> raises exception
            db.Entry(director).Property(x => x.Name).IsModified = true;
        }
    
        db.SaveChanges();
    }
    

    。Attach()方法引发InvalidOperationException异常,表示

    Attaching an entity of type 'CompanyDatabase.Employee' failed because
    another entity of the same type already has the same primary key value.
    This can happen when using the 'Attach' method or setting the state of
    an entity to 'Unchanged' or 'Modified' if any entities in the graph have
    conflicting key values. This may be because some entities are new and have
    not yet received database-generated key values. In this case use the 'Add'
    method or the 'Added' entity state to track the graph and then set the state
    of non-new entities to 'Unchanged' or 'Modified' as appropriate.
    

    但使用Add()方法也会引发类似的异常。。。 有什么解决办法吗?

    P、 美国国防部对象正在正常更改。更改Director对象也可以,即如果用户为部门选择一个新的Director。仅更改Director(Employee)的非id字段是一个问题。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ivan Stoev    7 年前
    db.Employees.Attach(director); // --> raises exception
    

    异常消息表示上下文已包含(正在跟踪) Employee 具有相同PK的对象( Id == director.Id )。因此,与其创建新对象( new Employee() )您需要使用现有对象(EF使用 参考标识 ,即不允许两个不同的实体 实例 有一个相同的PK)。

    这样做的标准方法是 Find 方法,该方法将返回当前跟踪的具有该PK的对象,或从数据库中加载该对象。因此,代码应该是这样的:

    if (dirNameChanged)
    {
        var director = db.Employess.Find(currentDept.DirectorId);
        director.Name = tbDirName.Text.Trim();
    }
    

    请注意,没有必要 Attach 它或操纵实体/属性状态-返回的对象由上下文附加和跟踪,因此任何属性值更改都会自动确定。

    推荐文章