【问题标题】:Insert data into related tables with entity framework使用实体框架将数据插入相关表中
【发布时间】:2018-02-14 23:29:48
【问题描述】:

我有两个相关的表 ProcessBatches 和 Transfers

首先,我必须在ProcessBatches 中插入一条记录,然后在Transfers 中插入一条记录。 我正在使用以下代码:

transferData.ProcessBatch = Context.ProcessBatches.Add(processBatchData);
Context.Transfers.Add(transferData);
Context.SaveChanges();

我的问题:在最坏的情况下,是否会在 ProcessBatches 中插入一条记录,但在 Transfers 中没有插入一条记录?

我的另一个想法:首先,将记录插入ProcessBatches,然后询问id,最后插入Transfers(如果id生成正确)

注意:两个表的id都是自动生成的。

【问题讨论】:

  • SaveChanges 在单个数据库事务中执行所有修改,因此您所要求的可能不会发生。

标签: entity-framework entity-framework-6


【解决方案1】:

我认为你需要这样做:

transferData.ProcessBatch = processBatchData;
Context.Transfers.Add(transferData);
Context.ProcessBatches.Add(processBatchData);
Context.SaveChanges();

我相信 Add 是一个 Void 方法,所以它不会返回任何东西。在您的代码中,您基本上是将 transferData.ProcessBatch 设置为 null。

【讨论】:

  • add方法返回一个实体
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多