Saturday 15 September 2012

c# - Handle a Dynamic Select With Dyanmic Linq -


I am using the dynamic link library which describes Scott Guthrie.

Examples of Scott Guthrie are great and I used dynamic where there is a lot of statements

Now, though, I have to face a situation where I am moving selectively The functionality has to be used by Scott Guthrie to show a screenshot of this functionality (in the very last screenshot in the article), but very cleverly it never explains.

The problem is, though code compilation I run, I do not think how it can work in any useful way. Maybe with reflection?

Here is an example (Remember, you should use the Danish Linen Library which is described in the above article, this is not the usual Linq System.Linq).

In my sample here, I have a user table with the UserId, FirstName, and LastName fields, but it does not really matter which database you use to reproduce this issue Too easy. Here's my sample code:

First of all, make sure that you have a description of the experiment at the top:

  System.Linq.Dynamic;  

You can then run the following code:

 using  (DataClasses1DataContext dcdc = New DataClasses1DataContext ()) {var x = dcdc.Users.Select ("New UserId, FirstName, LastName"); Foreign (different items in X) {console. WrightLine (item.ToString ()); }}  

As you can see, it compiles and runs just fine. You get all your records back from the database. However, there is actually no way for anonymous type members access .

Because the selection query is a string, because there is no type of guess at design time. So I can not write:

  console WrightLine (item.UserId);  

The compiler does not know if the name of the unknown type of items is UserId, then this code will not be compiled (even if you stop the debugger for you. During that you will see that the Debug Window observes that UserID is a member of FirstName and LastLamem.

Therefore .. How is this supposed to work? How do you gain access to members of anonymous type?

This data-band Will work fine for Icing (I suspect that this is the use-case to use it), which uses reflection under the hood. It will work fine with 4.0 in <4.0> Dynamic .

  foreach (dynamic item in x) {Console.WriteLine (item.UserId);}  

Also ... reflection or TypeDescriptor .

  foreach (commodity object in x) {console.light line (item. Gate type) GetProperty ("UserId"). GetValue (item, empty)) ;}  

No comments:

Post a Comment