Update data using LINQ

2

I've read that LINQ should be used for queries, but in the context below, the best way I found to update was using let .

var produtos = from o in orcItens    
    join p in Produtos on o.Id equals p.Id   
    let x = p.Estoque -= o.Quantidade
    select p;
  • Produtos is a IQueryable<> class that will be persisted.
  • orcItens is a list of ids , quantidade of products sold

Is there another way to update the data, for example using lambda ?

I tried to use foreach but could not get the grouped data.

    
asked by anonymous 02.01.2016 / 02:18

2 answers

1

LINQ is a language for querying only, it "does not allow" you to make changes to collections of data.

So to solve your problem you would ideally make a query for the "products" that correspond to the "budgets", put this result into an object and at the end of the query join all those objects into a collection. You would then use a foreach in this collection to update the data.

See the example below how to do this. Assuming you have the classes below:

public class Produto
{
    public int Id { get; set; }
    public int Estoque { get; set; }
}

public class Orcamento
{
    public int Id { get; set; }
    public int Quantidade { get; set; }
}

Define a class to match the corresponding "product" and "budget":

public class ProdutoOrcamento
{
    public Produto Produto { get; set; }
    public Orcamento Orcamento { get; set; }
}

Query, store the result, and through a foreach update the data in the Product instance:

var produtosOrcamentos = (from o in orcamentos
                          join p in produtos on o.Id equals p.Id
                          select new ProdutoOrcamento { Produto = p, Orcamento = o });

foreach (var i in produtosOrcamentos)
{
    i.Produto.Estoque = i.Orcamento.Quantidade;
}
    
02.01.2016 / 12:48
2

LINQ - Language-integrated QUERY

Query - > Inquiry

It's possible, but LINQ was created for queries. Do not try to subvert your function, especially without thoroughly mastering its operation and the consequences of doing so.

Go from foreach (command) and be happy. Obviously you can use LINQ to select what to upgrade.

Be careful not to complicate the design of the application just to make it easier to use LINQ. Do the best for the model. If LINQ does not fit into it, it's bad luck with LINQ.

    
02.01.2016 / 12:27