如何更新多行,一次使用linq到sql? [英] how to update the multiple rows at a time using linq to sql?
问题描述
表:
id userid friendid name status
1 1 2 venkat false
2 1 3 sai true
3 1 4 arun false
4 1 5 arjun false
if用户发送userid = 1,friendids = 2,4,5 status = true
if user sends userid=1,friendids=2,4,5 status=true
请告诉我有关如何更新上述所有friendids状态的查询。 [2,3,4 at a time]。
please tell me the query for how to update the above all friendids status is true. [2,3,4 at a time].?
谢谢
推荐答案
要更新一列,有一些语法选项:
To update one column here are some syntax options:
选项1
var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>a.status=true);
db.SubmitChanges();
}
选项2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>a.status=true);
db.SubmitChanges();
}
选项3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
}
db.SubmitChanges();
}
更新
根据评论的要求,显示如何更新多个列可能是有意义的。所以我们来说说这个练习的目的,我们不只是要更新状态
。我们要更新 name
和 status
其中 friendid
是匹配。以下是一些语法选项:
As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status
at ones. We want to update name
and status
where the friendid
is matching. Here are some syntax options for that:
选项1
var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
选项2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
选项3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
some.name=name;
}
db.SubmitChanges();
}
更新2
在答案我使用LINQ to SQL,在这种情况下,提交数据库的用法是:
In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:
db.SubmitChanges();
但是,对于实体框架来承诺更改:
But for Entity Framework to commit the changes it is:
db.SaveChanges()
这篇关于如何更新多行,一次使用linq到sql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!