[英]Entity Framework - New child entities not added to database on saving parent entity (only in production environment)
我在一個應用程序中面臨一個奇怪的問題。 我有以下代碼更新父實體並添加新的子實體。
Item item = db.Items.Find(Id);
if (newSubItems.Count() > 0)
{
newSubItems.ForEach(x =>
{
var subItem = new SubItem();
subItem.Name = x.Name;
item.SubItems.Add(subItem);
});
}
item.ModifiedAt = DateTime.Now;
item.ModifiedBy = UserId;
db.Entry(item).State = EntityState.Modified;
using (var s = db.Database.BeginTransaction(isolationLevel: IsolationLevel.RepeatableRead))
{
await db.SaveChangesAsync();
s.Commit();
logger.info("Updated successfully.");
}
此代碼在我的本地環境中正常工作。 如果我提供新的子項,則會將這些子項成功添加到相應的表中。
模型如下。
public partial class Item
{
public Item()
{
this.SubItems = new HashSet<SubItem>();
}
public int Id { get; set; }
public DateTime ModifiedAt { get; set; }
public int ModifiedBy { get; set; }
public virtual ICollection<SubItem> SubItems { get; set; }
}
public partial class SubItem
{
public int Id { get; set; }
public string Name { get; set; }
public int ItemId { get; set; }
public Item Item { get; set; }
}
但是,這在我的生產環境中無法正常工作。 父實體已更新,但如果沒有現有子實體,則不會添加新的子實體。 我檢查了日志,我可以看到“已成功更新”已被記錄。 如果父級至少有1個子實體,則成功添加新的子實體。
所以現在作為生產環境中的一種解決方法,我在使用下面的代碼進行第一次保存操作后再次重新添加子項。
int subItemsCount = db.SubItems.Where(a => a.ItemId == item.Id).Count();
if (subItemsCount == 0 && newSubItems.Count() > 0)
{
logger.info(string.Format("Sub-items are not added for Id - {0}. Adding those again.", item.Id));
newSubItems.ForEach(x =>
{
var subItem = new SubItem();
subItem.Name = x.Name;
subItem.ItemId = item.Id;
db.SubItems.Add(subItem);
});
await db.SaveChangesAsync();
logger.info(string.Format("Sub-items re-added successfully for Id - {0}.", item.Id));
}
現在,在查看生產環境中的日志時,我可以看到多次記錄消息“未為Id添加子項”,並且在第二次保存操作中成功添加了子項。
想知道是否有人知道在特定環境中這種奇怪行為的原因。
在你的第一種方法中,你應該在item.SubItems.Add()
之前檢查item.SubItems
是否為null。
如果為null,則初始化為item.SubItems = new ICollection<SubItem>();
在第二種方法中,在此代碼塊中,您沒有分配ItemId
newSubItems.ForEach(x =>
{
var subItem = new SubItem();
subItem.Name = x.Name;
subItem.ItemId = item.Id;/* missing line*/
db.SubItems.Add(subItem);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.