Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ select query with Anonymous type and user Defined type

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

like image 962
Muhammad Nasir Avatar asked Sep 08 '15 06:09

Muhammad Nasir


3 Answers

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
like image 173
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet


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.

like image 26
Dennis Avatar answered Sep 18 '22 19:09

Dennis


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.

like image 24
Muhammad Nasir Avatar answered Sep 17 '22 19:09

Muhammad Nasir