[英]Entity Framework 6- Saving data in a transaction
我需要一些幫助來了解我們要在實體框架中解決的情況。
我們正在嘗試更新兩個表1.映射表(兩個外鍵= ProductId和anotherId)2.在表中創建新記錄(在Product中調用,生成的主鍵是productId)
我們要確保產品表和映射表都已成功更新,否則,事務角色將返回。
我們將單筆交易用作
using (var context = new SomeContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{ //Create the record to be saved
var product = new Product{ // set the data}
var newProductId = context.SaveChanges();
//Update the Mapping Table
var anotherData = context.AnotherTable.where(x => x.id = anotherId).FirstOrDefault();
var productData = context.Product.where(x => x.id = newProductId).FirstOrDefault();
//Create the Mapping Table record
productData.AnotherDatas.Add(anotherData);
context.SavceChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
但是問題是
var productData = context.Product.where(x => x.id = newProductId).FirstOrDefault();
返回空值,我認為這是由於未提交事務這一事實。
如何克服這種情況? 如何創建映射記錄並使用新創建的ID? 在同一事務中運行多次保存會導致錯誤嗎?
您應該將product
添加到上下文中以保存它:
context.Product.Add(product);
context.SaveChanges();
另外, SaveChanges()
返回已更改記錄的計數,因此請查看product.id
以在保存后檢索插入的記錄ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.