【问题标题】:Updating an entity object with relation to another table-object (NxN) (Inserting, deleting)更新与另一个表对象 (NxN) 相关的实体对象(插入、删除)
【发布时间】:2018-08-30 10:52:18
【问题描述】:

将实体用于具有 NxN 关系的表(到另一个表),我无法更新第一个表对象(其中包含第二个表),因为程序显示与第二个表相关的异常消息,它说第二个表中有一条具有相同 PK 的记录(但我并没有更新第二个表本身,我正在更新 NxN 表,这意味着两个表之间的关系)。

这是场景:

TABLE1 - EntityObject1

属性1 int

属性2字符串

Attribute3 字符串

Attribute4 List(EntityObject2)

TABLE2 - EntityObject2

属性1 int

属性2字符串


所以:

var previous = context.TABLE1.Include(path => path.TABLE2)
      .Where(p => p.Attribute1 == updateElement.Attribute1).FirstOrDefault();
previous.Attribute4 = updateElement.Attribute4;
context.SaveChanges();

不像我说的那样工作。

尝试的另一种方法是:

First - 从上下文中删除前一个,然后保存上下文。

第二次 - 添加 updateElement 和 Save 上下文(不关心 PK 更改的事实)

有没有简单的方法来实现这一点?

完全迷路了……谢谢你们。

【问题讨论】:

  • 能否请您发布表 1 和表 2 的实际类定义。在您的通用示例中, INCLUDE 将直接引用 List 而不是 Table2 的名称。 Attribute1 = update 也会失败,需要 ==
  • @JohnWhite 第一个 - 因为它就是这样。属性 4 是 Table2 的对象列表(我正在使用实体,您应该检查我的问题的标签)。第二个——真的是男人吗?那没有意义。我不是在比较对象... C´Mon... 无论如何,感谢您的回复家伙...
  • p => p.Attribute1 = updateElement.Attribute1 是比较iirc
  • 在您的第一点上,List(Table2) 也被命名为 Table2?好的
  • @JohnWhite 不要小孩子...谢谢,这是我的错。干杯队友

标签: c# asp.net entity-framework entity-framework-6 entity


【解决方案1】:

嗯,终于找到了。我发布了帮助他人实现它的想法,至少,使用这种方式:

注意:我们必须使用事务来一步处理操作。

用于插入

我像往常一样生成对象 - 表 1,对于属性 4,我生成对象列表 - 表 2(先附加),然后将列表分配给属性 4...

(using context = new Dbcontext())
{
  using (var transaction = context.Database.BeginTransaction(IsolationLevel.Serializable))
  {
    Table1 object1 = new Table1
    {
      Attribute1 = 1, //(autoincrement really)
      Attribute2 = "random value",
      Attribute3 = "random value",
    };

    foreach (Table2 obj2 in NewValues)
    {
      Table2 o = new Table2() {Attribute1 = obj2.int, Attribute2 = obj2.string};
      context.Table2.Attach(o);
      object1.Attribute4.Add(o);
    }
  }
}

用于更新

我只是擦除,稍后插入。


另一种插入方式:

将列表存储在临时列表中 将没有 Attribute4 的 Object1 添加到上下文中。 最后,将临时列表添加到 object1.Attribute4。

(using context = new Dbcontext())
{
  using (var transaction = context.Database.BeginTransaction(IsolationLevel.Serializable))
  {
    Table1 object1 = new Table1
    {
      Attribute1 = 1, //(autoincrement really)
      Attribute2 = "random value",
      Attribute3 = "random value",
    };

    List<Table2> tempTable2 = new List<Object2>();
    foreach (Table2 obj2 in NewValues)
    {
      Table2 o = new Table2() {Attribute1 = obj2.int, Attribute2 = obj2.string};
      tempTable2.Add(o);
    }

    context.Table1.Add(object1);
    context.SavesChanges();

    Table1 object11 = context.Table1.First(o => o.Attribute1 == object1.Attribute1);
    object11.Attribute4 = tempTable2
    context.SavesChanges();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    相关资源
    最近更新 更多