EF Core how to increment a list of already recorded objects

Asked

Viewed 41 times

1

I am implementing a Web Api and I am using EF Core in the infrared layer. I have the related entities Table and Tableprecoitem, I wonder if to increment the property Tableprecoitem of an entity Table that is already saved, I need to do some specific configuration?

I’m doing like this:

   public override void Add(TabelaPreco tabela)
        {

            if (_dbSet.Any(tb => tb.Id == tabela.Id))
            {
                var table = _dbSet.Where(tb => tb.Id == tabela.Id)
                    .Include(tbi => tbi.Items).First();

                table.Items = tabela.Items;

                _dbSet.Update(table);

             }
            else
            {
                _dbSet.Add(tabela);
            }

            _context.SaveChanges();

        }

No Typeconfiguration

  builder.HasMany(p => p.Items)
.WithOne(itens => itens.TabelaPreco)
.HasForeignKey(fk => fk.TabelaPrecoId);

1 answer

0

I believed Ef would automatically increment the list, but from what I saw, it doesn’t. So I solved this with a "foreach" to check if the item does not exist and add it and with the Currentvalues.Setvalues method to edit existing items.

                foreach (var item in tabela.Items)
                {
                    var ItemExisting = _context.Set<TabelaPrecoItem>().Find(item.Id);

                    if (ItemExisting == null)
                    {
                        _context.TabelaPrecoItem.Add(item);
                    }
                    else
                    {
                        _context.Entry(ItemExisting).CurrentValues.SetValues(item);
                    }
                }
/*...*/

   _context.SaveChanges();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.