1

我是 Entify Framework 的新手,所以这可能是一个非常基本的问题。在 WinForms 应用程序中,我有一个工作正常的数据输入页面,直到我添加一个列表框并尝试使用已做出的选择来更新数据库。

在表单上,​​用户选择要上传的文件并指定一个或多个可以访问该文件的部门。这是我认为它会起作用的方式:

using (var ctx = new FCEntities())
{
  var batch = new Batch() { Description = txtDescription.Text, Filename = filename, Departments = (System.Data.Objects.DataClasses.EntityCollection<Department>)lstDepartments.SelectedItems };
  ctx.AddToBatches(batch);
  ctx.SaveChanges();
}

但是当这不起作用时,我做了一些研究并了解到我无法将 SelectedItems 转换为 EntityCollection,因此我决定将原始集合中的项目复制到新集合中,然后按如下方式使用新集合:

using (var ctx = new FCEntities())
{
  var departments = new System.Data.Objects.DataClasses.EntityCollection<Department>();

  foreach (var department in lstDepartments.SelectedItems)
  {
    departments.Add((Department)department);
  }

  var batch = new Batch() {Description = txtDescription.Text, Filename = filename, Departments=departments };
  ctx.AddToBatches(batch);
      ctx.SaveChanges();

}

这也不起作用,并在部门上给出了这个错误。添加行:

“无法将附加到 ObjectContext 的对象添加到不与源对象关联的 EntityCollection 或 EntityReference 中。”

我不明白,因为在我看来,部门对象没有附加到 ObjectContext?我显然缺少一些基本的东西,所以任何建议和/或其他人如何做到这一点的例子的链接都将不胜感激。

4

1 回答 1

1

我想留下一个答案,以防有一天其他人遇到这个问题。Wiktor 留下的评论帮助我找到了正确的方向。我认为我缺乏基本的理解,所以我在 MSDN 上做了一些阅读,并能够解决我的问题。

The datamodel behind this existed of three tables: Batches, Departments, and Batches_Departments which allowed for a many to many relationship between Batches and Departments.

The problem with my original code/logic, in a nutshell, was that the Department objects in the ListBox were associated with a different context than the one I was using in my Save method. EF didn't like this for obvious reasons (at least now they are obvious), so in the save method I used the ID from the selected Departments to get a reference to the same Department in the current context. I could then add this Department to the newly created batch.

Here's what the code now looks like:

using (var ctx = new FCEntities())
{
  var batch = new Batch() { Description = txtDescription.Text, Filename = filename};

  foreach (var department in lstDepartments.CheckedItems)
  {
    var dept = (from d in ctx.Departments where d.DepartmentID == ((Department)department).DepartmentID select d).First();
    batch.Departments.Add(dept);
  }

  ctx.Batches.AddObject(batch);
  ctx.SaveChanges();
}

Hopefully this helps someone else who is dealing with the same issue.

于 2012-06-27T12:47:23.610 回答