Do an update with lambda

Asked

Viewed 2,652 times

7

I have a query in lambda that returns me a list of data. I wonder how I do to update this table of BD using lambda?

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

  • Are you using some ORM?

  • 1

    You can put the code that brings the selection of the object, please?

  • type: update table set meu_field = new_value, but only in lambda. Entity use 6

  • 1

    Man, this is a lousy practice. What is the need for you to make a update manual using EF6?

  • @pnet analyze the answers and check if they answer your question?

  • So Morrison, what I really seek are good practices. Your comment I liked, but I stumble on my limitations in the use and knowledge of EF.

Show 1 more comment

4 answers

6

Update

In the Nhibernate 5.0 the following functionality has been included: Modifying entities Inside the database, that implements something similar to the one sought in this question: Updating entities, which would be the possibility of a similar implementation to that:

using NHibernate.Linq;
...    

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

Which would be equivalent to an 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 similar to that:

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

But unfortunately I have some bad news for you:

These "yet" approaches do not exist, so I recommend that follow the answers already exist (the most complete in my opinion is the @Harrypotter)

I’ve also looked for an approach similar to yours with Nhibernate, here, and found that both Lambda and Linq, are geared to queries (Query s), and not to "data change routines";

Perhaps in the near future, LINQ, LAMBDA and Orms will be incorporated into something that allows this. But for now the answer is no, there is no way.

On SOEN, there are also posts talking about this, here, with good approaches.

5


To update a list with Lambda Expression would be like in this example:

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 seek the information, then make a ForEach and changes 1 or more fields and at the end of a SaveChanges(); Could be made a For/ForEach simpler, but by question that is way Lambda

  • A very basic question. With db.Savechanges(), do I really not give an Insert? This is my question.

  • Insert only when one add, when you recover is an update

  • 1

    Okay, so it’s more than settled.

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();               
        }
  • A very simple example of update. I get the status (my class with several attributes) and change one of the attributes. Before "Savechanges()" I signal that my object has undergone a change.

2

I made a complete example of a Detail controller that updates any record. When entering the registry, I check if everything is ok. Then I take the PK (Primary Key) from the registry and search it for Find. If you do not find a mistake and go to the Home site.

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

After all, I show the record 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 });
  }
}

Lambda:

var registro = db.Registro.Where(w => w.RegistroID == model.RegistroID).First();   
  • Okay, Marlon, but that’s not lambda. I’d like to know how to do with lambda Expression.

  • Set in my post. But why don’t you use Find? Find uses the table’s PK. If composed, set all items apart by ','

  • I would like to close this post, but I didn’t get it right yet. I will edit the post to better understand.

Browser other questions tagged

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