score:11

Accepted answer

if i understand you correctly, you're wondering, how linq provider can set properties of anonymous object, since they are "true" read only properties (there's no any private set, but get only)?

when you call select extension method for iqueryable<t>, it accepts an expression of type expression<func<t, tresult>. if you'll write some stub for select you can look into the generated expression, using debugger:

public static class myextensions
{
    public static void myselect<t, tresult>(this iqueryable<t> query, expression<func<t, tresult>> projection)
    {
        system.diagnostics.debug.writeline(projection);
    }
}

the difference is in how compiler generates lambda expressions for named types and anonymous types. when you call select for named type, expression will look like this:

{_ => new person() {id = _.id, name = _.name}}

that is, firstly new person object will be constructed, and then members will be initialized (memberinit expression).

but when you call select for anonymous type, expression will be built as constructor call (new expression):

{_ => new <>f__anonymoustype0`2(a = _.id, b = _.name)}

linq provider compiles these lambdas into delegates, when materializing query results, and ultimately just calls constructor for anonymous type.

score:2

i found following difference in with anonymous type result of a linq result.

  1. result is not edit able e.g. if we assign value to a gridview it will be read only.

  2. problem with scope of an anonymous object.we can't pass the type to another method. define a parameter of type var; var must always be followed by an initialization expression.

if you need result only in current context for read only purpose use anonymous query . if you need result in other function the you have to define type of object. the object type after new will be created with properties you want to get from result define then in curly braces {} . it is not necessary to initialize all value of model class.

score:17

the error you're getting really doesn't have anything to do with linq. you can see the same thing without using linq at all:

var anonymous = new { name = "fred" };
anonymous.name = "joe"; // error, as properties of anonymous types are read-only

so if you want to modify the objects fetched by your linq query, you shouldn't use anonymous types. but both linq queries are statically bound - anonymous types are still fully known at compile-time, and the compiler applies normal type restrictions to them. for example:

var anonymous = new { name = "fred" };
console.writeline(anonymous.foo); // error: no property foo
int bar = anonymous.name; // error: no conversion from string to int

Related Query

More Query from same tag