Reputation: 95
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?
Upvotes: 1
Views: 60
Reputation: 20373
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.
Upvotes: 1
Reputation: 9089
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();
Upvotes: 2