LINQ to Entities how to update a record

后端 未结 4 1044
粉色の甜心
粉色の甜心 2021-02-01 01:58

Okay, so I\'m new to both EF and LINQ. I have figured out how to INSERT and DELETE but for some reason UPDATE seems to escape my grasp.

Here is a sample of my code:

相关标签:
4条回答
  • 2021-02-01 02:26

    In most cases @tster's answer will suffice. However, I had a scenario where I wanted to update a row without first retrieving it.

    My situation is this: I've got a table where I want to "lock" a row so that only a single user at a time will be able to edit it in my app. I'm achieving this by saying

    update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'

    The reason being, if I were to simply retrieve the row by ID, change the properties and then save, I could end up with two people accessing the same row simultaneously. This way, I simply send and update claiming this row as mine, then I try to retrieve the row which has the same properties I just updated with. If that row exists, great. If, for some reason it doesn't (someone else's "lock" command got there first), I simply return FALSE from my method.

    I do this by using context.Database.ExecuteSqlCommand which accepts a string command and an array of parameters.

    Just wanted to add this answer to point out that there will be scenarios in which retrieving a row, updating it, and saving it back to the DB won't suffice and that there are ways of running a straight update statement when necessary.

    0 讨论(0)
  • 2021-02-01 02:37

    //for update

    (from x in dataBase.Customers
             where x.Name == "Test"
             select x).ToList().ForEach(xx => xx.Name="New Name");
    

    //for delete

    dataBase.Customers.RemoveAll(x=>x.Name=="Name");
    
    0 讨论(0)
  • 2021-02-01 02:38

    They both track your changes to the collection, just call the SaveChanges() method that should update the DB.

    0 讨论(0)
  • 2021-02-01 02:45

    Just modify one of the returned entities:

    Customer c = (from x in dataBase.Customers
                 where x.Name == "Test"
                 select x).First();
    c.Name = "New Name";
    dataBase.SaveChanges();
    

    Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}

    0 讨论(0)
提交回复
热议问题