LINQ select query with Anonymous type and user Defined type

Muhammad Nasir picture Muhammad Nasir · Sep 8, 2015 · Viewed 16.8k times · Source

Anonymous class has read only properties in c#. Which is often used to to declare in linq select query to get particular values from database. In my code I have the following query.The thing that confused me selecting new object of anonymous class using new statement. I had a model class of StudentClerkshipsLogModel . When I Use model name the query result allow editing.

var query = (from entity in _tblStudentClerkshipsLog.GetQueryable()
             where entity.StudentID == intStudentID                             
             select new StudentClerkshipsLogModel
             {
                 StudentClerkshipID = entity.StudentClerkshipID,
                 StudentID = entity.StudentID,
                 ClerkshipID = entity.ClerkshipID,
             }).ToList();

When I did not mention type after new in select statement I am unable to exit. compiler raise an error . enonymous object is read only.

var query = (from entity in _tblStudentClerkshipsLog.GetQueryable()
             where entity.StudentID == intStudentID                             
             select new 
             {
                 StudentClerkshipID = entity.StudentClerkshipID,
                 StudentID = entity.StudentID,
                 ClerkshipID = entity.ClerkshipID,
             }).ToList()

my question is how linq bind the about two query differently . Both queries have dynamic binding or first one is is static.

Thanks

Answer

Jon Skeet picture Jon Skeet · Sep 8, 2015

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