1

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?

2
  • Sounds like RegionDescription is a read only property... What about the error is confusing you? It does not work in the lambda either since the lamda is checking equality (==), not performing assignment (=) Commented Jun 21, 2018 at 19:25
  • 5
    You also returned an anonymous type in the 2nd version. You need to return an actual object if you want to change the values. Commented Jun 21, 2018 at 19:26

2 Answers 2

2
 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();
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for answer and explanation, it works perfect! :)
@Danki Glad it worked out. Please mark Answered on one of the submissions.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.