How to create LINQ Expression Tree to select an anonymous type

前端 未结 9 729
夕颜
夕颜 2020-11-22 12:12

I would like to generate the following select statement dynamically using expression trees:

var v = from c in Countries
        where c.City == \"London\"
           


        
9条回答
  •  迷失自我
    2020-11-22 12:41

    The accepted answer is very useful, but I needed something a little closer to a real anonymous type.

    A real anonymous type has read-only properties, a constructor for filling in all of the values, an implementation of Equals/GetHashCode for comparing the values of each property, and an implementation ToString that includes the name/value of each property. (See https://msdn.microsoft.com/en-us/library/bb397696.aspx for a full description of anonymous types.)

    Based on that definition of anonymous classes, I put a class that generates dynamic anonymous types on github at https://github.com/dotlattice/LatticeUtils/blob/master/LatticeUtils/AnonymousTypeUtils.cs. The project also contains some unit tests to make sure the fake anonymous types behave like real ones.

    Here's a very basic example of how to use it:

    AnonymousTypeUtils.CreateObject(new Dictionary
    {
        { "a", 1 },
        { "b", 2 }
    });
    

    Also, another note: I found that when using a dynamic anonymous type with Entity Framework, the constructor must be called with the "members" parameter set. For example:

    Expression.New(
        constructor: anonymousType.GetConstructors().Single(), 
        arguments: propertyExpressions,
        members: anonymousType.GetProperties().Cast().ToArray()
    ); 
    

    If you used one of the versions of Expression.New that does not include the "members" parameter, Entity Framework would not recognize it as the constructor of an anonymous type. So I assume that means a real anonymous type's constructor expression would include that "members" information.

提交回复
热议问题