Update records using LINQ

后端 未结 8 1577
迷失自我
迷失自我 2020-12-04 17:24

I need to set a value in a table for a subset of rows. In SQL, I would do this:

UPDATE dbo.Person SET is_default = 0 WHERE person_id = 5

Is

8条回答
  •  一生所求
    2020-12-04 18:08

    I assume person_id is the primary key of Person table, so here's how you update a single record:

    Person result = (from p in Context.Persons
                  where p.person_id == 5
                  select p).SingleOrDefault();
    
    result.is_default = false;
    
    Context.SaveChanges();
    

    and here's how you update multiple records:

    List results = (from p in Context.Persons
                            where .... // add where condition here
                            select p).ToList();
    
    foreach (Person p in results)
    {
        p.is_default = false;
    }
    
    Context.SaveChanges();
    

提交回复
热议问题