Cra*_*aig 47 c# linq entity-framework
我需要在表中为行子集设置一个值.在SQL中,我会这样做:
UPDATE dbo.Person SET is_default = 0 WHERE person_id = 5
Run Code Online (Sandbox Code Playgroud)
有没有办法在LINQ中执行此操作?
我目前使用的是:
var result = (from p in Context.People....)
Run Code Online (Sandbox Code Playgroud)
符号.
有没有我可以使用的更新方法?或者我是否必须获取所有记录,然后在Foreach中逐个更新它们?
如果可能的话,这是最有效的方式吗?
(from p in Context.person_account_portfolio where p.person_id == personId select p)
.ToList()
.ForEach(
x =>
x.is_default =
false);
Run Code Online (Sandbox Code Playgroud)
eka*_*kad 54
我假设person_id是Person表的主键,所以这里是你如何更新单个记录:
Person result = (from p in Context.Persons
where p.person_id == 5
select p).SingleOrDefault();
result.is_default = false;
Context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
以下是更新多条记录的方法:
List<Person> 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();
Run Code Online (Sandbox Code Playgroud)
Cra*_*aig 53
这效果最好.
(from p in Context.person_account_portfolio
where p.person_id == personId select p).ToList()
.ForEach(x => x.is_default = false);
Context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)
作为对已接受答案的补充,您可能会发现在使用LINQ方法语法时,您的代码看起来更加一致:
Context.person_account_portfolio
.Where(p => person_id == personId)
.ToList()
.ForEach(x => x.is_default = false);
Run Code Online (Sandbox Code Playgroud)
.ToList()是必要的,因为.ForEach()只在on List<T>,而不是on上定义IEnumerable<T>.请注意.ToList(),在执行循环之前,将执行查询并从数据库加载所有匹配的行.
| 归档时间: |
|
| 查看次数: |
183242 次 |
| 最近记录: |