What is difference between 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();
}
When I trying to make update on change2 in foreach loop i got error:
Property or indexer '......' cannot be assigned to -- it is read only
It works on previous version with lambda. How Can i change it to work?
var change2 = (from r in context.Regions
where r.RegionDescription == "East"
select new {r.RegionID, r.RegionDescription }).ToList();
You are returning an anonymous type. Anonymous type properties are read-only. If you want to change the value, you need to return an actual type that you have defined.
You can either new
something else like new Region
or just return 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();
change2 returns an anonymous type which is immutable. To amend the value, you need to write:
var change2 = (from r in context.Regions where r.RegionDescription == "East" select r).ToList();
Which is equivalent to change1.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.