从父实体更新子实体

时间:2019-07-26 17:35:15

标签: c# json asp.net-mvc entity-framework asp.net-core

根据以下情况,我想从父实体更新子实体。

我按照以下方法解决了这个问题。

  1. 父级的子实体从数据库中删除。
  2. 父级的新子实体从数据库中添加。

那是真的吗?

    public int SaveBasket(Addition addition)
    {
        var entity = ApplicationDbContext.Additions.Include(x => x.Basket).SingleOrDefault(x => x.AdditionId == addition.AdditionId);

        //Remove Basket
        if (entity.Basket.Count > 0)
        {
            foreach (var item in entity.Basket)
            {
                context.Entry(item).State = EntityState.Deleted;
            }

            ApplicationDbContext.SaveChanges();
        }

        //Add new basket entities from posting json data
        entity.Basket = addition.Basket;

        return ApplicationDbContext.SaveChanges();
    }

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找以下内容:

    public int SaveBasket(Addition addition)
    {
        var entity = ApplicationDbContext.Additions.Find(addition.AdditionId); // Find by primary key

        //Remove Basket
        if (entity.Basket.Count > 0)
        {
            entity.Basket.Clear(); // Empty out the basket

            ApplicationDbContext.SaveChanges();
        }

        //Add new basket entities from posting json data
        addition.Basket.ForEach(b => entity.Basket.Add(b)); // Add the items

        return ApplicationDbContext.SaveChanges();
    }

很难说出您的数据结构是什么,但这应该有所帮助。

更新

从您的评论看来,您似乎要删除整个basket记录。

    public int SaveBasket(Addition addition)
    {
        var baskets = ApplicationDbContext.Basket.Where(b => b.AdditionId == addition.AdditionId);

        //Remove Basket
        ApplicationDbContext.Basket.RemoveRange(baskets);
        ApplicationDbContext.SaveChanges();
        ApplicationDbContext.Basket.AddRange(addition.Basket);
        return ApplicationDbContext.SaveChanges();
    }

答案 1 :(得分:0)

根据模型的外观,您也许可以执行此操作以删除和添加子项。

public int SaveBasket(Addition addition)
{
    var dbAddition = ApplicationDbContext.Additions
        .Include(x => x.Basket)
        .SingleOrDefault(x => x.AdditionId == addition.AdditionId);

    ApplicationDbContext.Basket.RemoveRange(dbAddition.Basket);
    ApplicationDbContext.Basket.AddRange(addition.Basket);

    return ApplicationDbContext.SaveChanges();
}