Make an update with lambda

7

I have a query in lambda that returns me a list of data. I would like to know how do I update this DB table using lambda?

Let's say, I have a Table called T_PDV and in it a flag field, where milestone LIDO = 1 and if it is not LIDO = 0. This field, when inserted records in this table, it is marked with 0. After a given situation , it should be marked 1. How do I do this update? Update is only in this field.

    
asked by anonymous 02.06.2014 / 18:51

4 answers

5

To make an update to a list with Lambda Expression would look like this:

using (GenericsEntities db = new GenericsEntities())
{
    //Buscando as informações
    var dta = DateTime.Parse("01/01/2013");
    var dados = db.tbDatas.Where(x => DbFunctions.TruncateTime(x.Data) == dta).ToList();

    //Alterando as informações
    dados.ForEach(x =>
    {
        x.Data = x.Data.AddDays(-3),
        x.Nome = "Alterando nome";      
    });

    //Salvando as informações que foram alteradas
    db.SaveChanges();

}

That is, when I look for the information, then make a ForEach and change 1 or more fields and at the end of a SaveChanges(); It could be done a For/ForEach simpler, but, for the question this is Lambda form %

    
02.06.2014 / 21:06
6

Update

In NHibernate 5.0 the following functionality has been added: Modifying entities inside the database , which implements something similar to the one searched for in this question: Updating entities , which would be the possibility of an implementation similar to this:

using NHibernate.Linq;
...    

session.Query<Cat>()
    .Where(c => c.BodyWeight > 20)
    .UpdateBuilder()
    .Set(c => c.BodyWeight, 20)
    .Update();

That would be equivalent to a SQL like:

UPDATE Cat
SET BodyWeight = 20
WHERE BodyWeight > 20;

I think I know the answer you want to read:

With LINQ something in that idea:

// Atenção isso não existe
(from entity in db.Registro update entity.Flag = 1 where entity.Id = 1).Apply();

Or with Lambda something like this:

// Atenção isso também não existe
db.Registro.Where(t => t.Id = 1).Update(t => t.Flag = 1);

But unfortunately I have bad news for you:

These approaches "still" do not exist, so I recommend following the answers already exist (the most complete one in my opinion is @ HarryPotter )

I've also looked for a similar approach to yours with NHibernate,

p>

Maybe in the near future, something that will allow it to be incorporated into LINQ, LAMBDA and ORMs. But for now the answer is no, there is no way.

In SOEN, there are also posts talking about it, here , with good approaches.

    
09.06.2014 / 16:05
3
        using (dbContext dataContext = new dbContext()) {
            StatusInteracao status = dataContext.StatusInteracao.Where(s => s.Login == login).SingleOrDefault();

            status.StatusVisitouCount = dataContext.Visitou.Where(v => v.LoginFoiVisitado == login).Count();               

            dataContext.StatusInteracao.Attach(status);
            dataContext.Entry(status).State = System.Data.EntityState.Modified;
            dataContext.SaveChanges();               
        }
    
02.06.2014 / 19:24
2

I've done a complete example of a Detail controller that updates any record. When I enter the registry, I verify that everything is ok. Then I get the PK (Primary Key) from the registry and fetch it from Find. If you do not find it generates a mistake and it goes to the Home of the site.

The UpdateModel command takes the model data and puts it into the registro variable. Then it is marked as changed the registry and saves it in the database.

After all this, I show the registry again in the view.

public ActionResult Detalhar(Registro model)
{
  if (!ModelState.IsValid)
      return View(model);

  using (var db = new ERPContext())
  {
      var registro = db.Registro.Find(model.RegistroID);    
      if (registro == null)
      {
          TempData["MsgRetornoError"] = "Registro não encontrado!";
          return RedirectToAction("Index", "Home");
      }

      UpdateModel(registro);    
      db.Entry(registro).State = EntityState.Modified;
      db.SaveChanges();

      if (btnSubmit == "Excluir")
          return RedirectToAction("Index", controller);

      return RedirectToAction("Detalhar", controller, new { id = model.RegistroID });
  }
}

In lambda:

var registro = db.Registro.Where(w => w.RegistroID == model.RegistroID).First();   
    
02.06.2014 / 19:38