LINQ to Entities 如何更新记录
好的,我对 EF 和 LINQ 都是新手。我已经弄清楚如何插入和删除,但由于某种原因更新似乎逃脱了我的掌握。
这是我的代码示例:
EntityDB dataBase = new EntityDB();
Customer c = new Customer
{
Name = "Test",
Gender = "Male
};
dataBase.Customers.AddObject(c);
dataBase.SaveChanges();
上面创建并添加了一条记录就好了。
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
selext x).First();
dataBase.Customers.DeleteObject(c);
dataBase.SaveChanges();
上面有效地删除了指定的记录。
现在我该如何更新?我似乎无法在实体集合上找到“UpdateObject()
”方法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需修改返回的实体之一:
注意,您只能更新一个实体(扩展 EntityObject 的实体,而不是您使用
select new CustomObject{Name = x.Name}
等方式投影的实体)Just modify one of the returned entities:
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}
//用于更新
//用于删除
//for update
//for delete
它们都跟踪您对集合的更改,只需调用应该更新数据库的 SaveChanges() 方法。
They both track your changes to the collection, just call the SaveChanges() method that should update the DB.
在大多数情况下,@tster 的答案就足够了。但是,我有一个场景,我想更新一行而不先检索它。
我的情况是这样的:我有一个表,我想在其中“锁定”一行,以便一次只有一个用户能够在我的应用程序中编辑它。我通过说
update items set status = 'in use', lastuser = @lastuser, lastupdate = @updatetime where ID = @rowtolock and @status = 'free'
原因是,如果我只需按 ID 检索行,更改属性然后保存,最终可能会导致两个人同时访问同一行。这样,我只需发送并更新,声明该行是我的,然后尝试检索与我刚刚更新的属性相同的行。如果该行存在,那就太好了。如果由于某种原因它没有(其他人的“锁定”命令首先到达那里),我只需从我的方法中返回 FALSE 。
我通过使用 context.Database.ExecuteSqlCommand 接受字符串命令和参数数组。
只是想添加这个答案来指出,在某些情况下,检索行、更新行并将其保存回数据库是不够的,并且有一些方法可以在必要时运行直接更新语句。
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.