change/change2 有什么区别?
using (var context = new NORTHWNDEntities())
{
var change = context.Regions.Where(r => r.RegionDescription == "East").ToList();
var change2 = (from r in context.Regions where r.RegionDescription == "East" select new {r.RegionID, r.RegionDescription }).ToList();
foreach (var p in change2)
{
p.RegionDescription = "West";
}
context.SaveChanges();
}
当我尝试在 foreach 循环中更新 change2 时出现错误:
Property or indexer '......' cannot be assigned to -- it is read only
它适用于使用 lambda 的先前版本。我怎样才能让它工作?
最佳答案
var change2 = (from r in context.Regions
where r.RegionDescription == "East"
select new {r.RegionID, r.RegionDescription }).ToList();
您返回的是匿名类型。匿名类型属性是只读的。如果要更改值,则需要返回已定义的实际类型。
您可以new
其他东西,比如new Region
或者只返回r
var change2 = (from r in context.Regions
where r.RegionDescription == "East"
select r).ToList();
var change2 = (from r in context.Regions
where r.RegionDescription == "East"
select new Region {.RegionID = r.RegionID,
.RegionDescription = r.RegionDescription }).ToList();
关于c# - 带有 LINQ 查询的 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976160/