0
votes

According to the scenario below, I would like to update child entities from parent entity.

I approached the problem as follows.

  1. Child entities of parent delete from database.
  2. New child entities of parent add from database.

Is that approach true way ?

    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

2 Answers

0
votes

I think you're looking for the following:

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

Hard to tell what your data structure is, but this should help.

Update

From your comment, it sounds like you want to remove the entire basket record.

    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();
    }
0
votes

Depending on what your models look like, you might be able to just do this for deleting and adding children.

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