【问题标题】:Entity framework many to many relation bottleneck in inserting data实体框架插入数据中的多对多关系瓶颈
【发布时间】:2011-02-24 19:59:47
【问题描述】:

我有一个视图向用户显示一个表单,用户应该上传一个文件并选择与之关联的所有类别。

负责提交数据的控制者应

  • 检索文件信息并 在文件类别中插入数据

  • 检索相关的类别 ID 和 将它们也插入到 表中 由 EF 抽象出来 插入文件和类别 ID。

这是我的问题,控制器只是获取有关类别的一些信息,而不是全部信息。基本上它只需要插入的 id

我不能用

        [HttpPost]
    public ActionResult SaveFile(File file, List<Category> Checkbox, HttpPostedFileBase FileUpload)
    {
        //some stuff
        //for example got the first category and named it to category1
        file.Categories.Add(category1)
    }

我问了一个人,他告诉我你必须选择你要插入的类别

这真的有必要吗?我只需要一个类别 id 和一个文件 id 来进行插入为什么我要向数据库发起另一个我并不真正需要的请求


我正在使用

  • EF 4
  • MVC 3

【问题讨论】:

    标签: asp.net-mvc entity-framework


    【解决方案1】:

    最好先选择类别,因为它会为您节省很多可能出现的问题,但这不是必需的。您可以使用虚拟类别对象:

      var category = new Category { Id = receivedId };
      file.Categories.Add(category);
    

    您只会创建新类别并设置其 PK。现在您需要处理文件插入,您必须明确指示 ObjectContext 仅插入文件(因为您的类别存在于数据库中):

    context.Files.Attach(file); // now whole object graph is attached but marked as Unchanged
    context.ObjectStateManager.ChangeObjectState(file, EntityState.Added); // mark only file entity as inserted
    context.SaveChanges();
    

    你也可以采取相反的方向:

    context.Files.AddObject(file); // all objects in object graph are marked for insertion
    foreach (var category in file.Categories)
    {
      // you don't want to insert categories again
      context.ObjectStateManager.ChangeObjectState(category, EntityState.Unchanged); 
    }
    context.SaveChanges();
    

    如果您知道所有类别都存在于您的数据库中,则此方案有效。如果您想在保存文件的同时插入新类别,您需要先查询类别或添加一些关于哪些类别是新的,哪些是现有的信息。

    【讨论】:

    • 我仍然想在抽象实体“CategoryFile”中插入一行,所以当我尝试你的方法时,结果是异常Unable to update the EntitySet 'CategoryFile' because it has a DefiningQuery and no &lt;InsertFunction&gt; element exists in the &lt;ModificationFunctionMapping&gt; element to support the current operation.
    • @Nadeem:在这种情况下,您的数据模型定义不正确。 Category 和 File 之间的连接表对于 EF 是只读的。您可能缺少该表中的主键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2011-12-17
    相关资源
    最近更新 更多