How to save in 2 tables at the same time

Asked

Viewed 469 times

4

Hello, I would like a help. I have this method to save the data in two tables.

 public void SalvarLocacao(Carrinho carrinho, Locacao locacao)
        {
            Item items = new Item();           
            foreach (var item in carrinho.ItensCarrinho)
            {                
                items.LocacaoId = locacao.LocacaoId;
                items.CacambaId = item.CacambaId;
                items.Quantidade = item.Quantidade;
                Db.Items.Add(items);                               
            }
            Db.Locacaos.Add(locacao);
            Db.SaveChanges();
        }

But at the time I save it saves only 1 item, and it is the last item, I would like to know how I do to save everything at once. Thank you !!

  • You’re saying if there are 3 items you’re saving 2 and the third one isn’t?

1 answer

1


This code doesn’t make much sense. If the items are part of a Locacao, you can save everything just by using the Locacao.

Anyway, I’m going to assume that for some reason, you need these items to come in Carrinho. That is to say:

    public void SalvarLocacao(Carrinho carrinho, Locacao locacao)
    {
        // Não entendi o que você quer fazer com isso, então removi.
        // Item items = new Item();           
        // foreach (var item in carrinho.ItensCarrinho)
        // {                
        //    items.LocacaoId = locacao.LocacaoId;
        //    items.CacambaId = item.CacambaId;
        //    items.Quantidade = item.Quantidade;
        //    Db.Items.Add(items);                               
        //}

        // Se um item do carrinho se relaciona com Locacao, basta você adicionar o item à Locacao.
        for (var item in carrinho.ItensCarrinho) 
        {
            if (!locacao.Items.Any(i => i.ItemId == item.ItemId))
            {
                locacao.Items.Add(item);
            }
        }

        Db.Locacaos.Add(locacao);
        // Isto salva a Locacao e todos os Itens relacionados a ela.
        Db.SaveChanges();
    }

Browser other questions tagged

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