简体   繁体   English

实体框架 - 未在保存父实体上添加到数据库的新子实体(仅在生产环境中)

[英]Entity Framework - New child entities not added to database on saving parent entity (only in production environment)

I am facing a weird issue in an application. 我在一个应用程序中面临一个奇怪的问题。 I have the following code which updates a parent entity and add new child entities. 我有以下代码更新父实体并添加新的子实体。

    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.");
    }

This code is working fine in my local environment. 此代码在我的本地环境中正常工作。 If I supply new sub-items, those are added successfully to the respective table. 如果我提供新的子项,则会将这些子项成功添加到相应的表中。

The models are given below. 模型如下。

    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; }
    }

However this is not working in my production environment as expected. 但是,这在我的生产环境中无法正常工作。 Parent entity is updated, but new child entities are not added if there are no existing child entities. 父实体已更新,但如果没有现有子实体,则不会添加新的子实体。 I checked the logs and I can see that "Updated successfully" is logged. 我检查了日志,我可以看到“已成功更新”已被记录。 If there is at-least 1 child entity for the parent, then new child entities are added successfully. 如果父级至少有1个子实体,则成功添加新的子实体。

So now as a work around in production environment, I am re-adding the sub-items again after the first save operation using the below code. 所以现在作为生产环境中的一种解决方法,我在使用下面的代码进行第一次保存操作后再次重新添加子项。

    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));
    }

Now at looking the logs from production environment, I can see that the message "Sub-items are not added for Id" is logged many times and sub-items are added successfully in the second save operation. 现在,在查看生产环境中的日志时,我可以看到多次记录消息“未为Id添加子项”,并且在第二次保存操作中成功添加了子项。

Wondering if any one know the reason for this weird behavior in specific environment alone. 想知道是否有人知道在特定环境中这种奇怪行为的原因。

In your first approach you should check if item.SubItems for null before doing item.SubItems.Add() on it. 在你的第一种方法中,你应该在item.SubItems.Add()之前检查item.SubItems是否为null。

If it is null then initialize like item.SubItems = new ICollection<SubItem>(); 如果为null,则初始化为item.SubItems = new ICollection<SubItem>();

In your second approach,in this code block you are not assigning ItemId 在第二种方法中,在此代码块中,您没有分配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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM