Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6236633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T10:53:04+00:00 2026-05-24T10:53:04+00:00

Help, I appeared to wondered off the path somewhat. After asking this question yesterday,

  • 0

Help, I appeared to wondered off the path somewhat.

After asking this question yesterday, I decided to take a look into expression trees. I found a nice little place to start and here is what I have so far:

  // Gets the property type
  ParameterExpression paramProperty = Expression.Parameter(property.PropertyType);
  // Gets the value from row[0] (SqlDataReader)
  ParameterExpression paramValue = Expression.Parameter(row[0].GetType());
  // really no clue, makes a property so to speak?
  MemberExpression prop = Expression.Property(paramProperty, property);
  // assigns the property the value from the SqlDataReader
  BinaryExpression assign = Expression.Assign(prop, paramValue);
  // adds to an expression list ready for compilation
  exps.Add(assign);
  // allows things to be executed sequentially?
  BlockExpression blockExpression = exps.Count > 0 ? Expression.Block(exps) : Expression.Block(Expression.Empty());
  // create the parameter array
  List<ParameterExpression> paramArr = new List<ParameterExpression>();
  paramArr.Add(paramProperty);
  paramArr.Add(paramValue);
  // get a lambda so I can compile this for re-use
  Expression<Action<T>> lamExp = Expression.Lambda<Action<T>>(blockExpression, paramArr);

First of all, are my comments right? I am piecing this information in the good old fashion way of a tutorial and msdn doc’s.

From the bits that I have been reading, I think I should have been able to compile this, store it in a dictionary with a type as the key and call it when I needed to. Eg.

  ConcurrentDictionary<Type, ??> ExpressionCache;
  if(ExpressionCache.ContainsKey(typeof(T))
  {
         // property is the variable of a foreach loop of type PropertyInfo
         ExpressionCache[typeof(T)](property); 
  } // else do the first piece of code...

So in summary,

  1. Am I heading down the right track?
  2. Are my comments about the Expressions correct?
  3. What type should I use for the concurrent dictionary?
  4. When I cache the reference, how do I pass different parameters to the lambda?

Any improvements or suggestions are welcome as long as the are explained well. I am trying to understand how it works not just to make it work 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T10:53:05+00:00Added an answer on May 24, 2026 at 10:53 am

    It sounds like you’re looking for commentary more than anything else…right?

    First of all, how will you have your SqlReader at compile time?

    // Gets the value from row[0] (SqlDataReader)
    ParameterExpression paramValue = Expression.Parameter(Type.GetTypeFromHandle(row[0].GetType()));
    

    Your lambda takes two parameters though…so something is wrong (Action takes one parameter).

    I would think that you really want is an Func<SqlDataReader, T>. That way, you give it your SqlDataReader and it produces a T. So:

    var list = new List<T>();
    // get a SqlDataReader
    while (reader.Read())
    {
        Func<SqlDataReader, T> readRow = GetReader<T>();
        list.Add(readRow(reader);
    }
    

    I would store your cache as

     ConcurrentDictionary<Type, Delegate> ExpressionCache;  // can't use T here since each Func will have a different T
    

    Then cast it to the appropriate delegate type for the caller upon retrieval (have your method take a generic parameter:

     public Func<SqlDataReader, T> GetReader<T>() 
     { 
         Delegate d;
         if(!ExpressionCache.TryGetValue(typeof(T), out d)
         {
             ExpressionCache[typeof(T)] = d = // build and compile lambda
         } 
         // cast to strong typed delegate...we don't want to have to DynamicInvoke...that's slow
         return (Func<SqlDataReader, T>)d;
     }
    

    So…as for your lambda builder/compiler:

            // hang on to row[string] property 
            var indexerProperty = typeof(SqlDataReader).GetProperty("Item", new[] { typeof(string) });
    
            // list of statements in our dynamic method
            var statements = new List<Expression>();
    
            // store instance for setting of properties
            ParameterExpression instanceParameter = Expression.Variable(typeof(T));
            ParameterExpression sqlDataReaderParameter = Expression.Parameter(typeof(SqlDataReader));
    
            // create and assign new T to variable: var instance = new T();
            BinaryExpression createInstance = Expression.Assign(instanceParameter, Expression.New(typeof(T)));
            statements.Add(createInstance);
    
            foreach (var property in typeof(T).GetProperties())
            {
                // instance.MyProperty
                MemberExpression getProperty = Expression.Property(instanceParameter, property);
    
                // row[property] -- NOTE: this assumes column names are the same as PropertyInfo names on T
                IndexExpression readValue = Expression.MakeIndex(sqlDataReaderParameter, indexerProperty, new[] { Expression.Constant(property.Name) });
    
                // instance.MyProperty = row[property]
                BinaryExpression assignProperty = Expression.Assign(getProperty, Expression.Convert(readValue, property.PropertyType));
    
                statements.Add(assignProperty);
            }
    
            var returnStatement = instanceParameter;
            statements.Add(returnStatement);
    
            var body = Expression.Block(instanceParameter.Type, new[] { instanceParameter }, statements.ToArray());
    
            /* so we end up with
             * T Read(SqlDataReader row)
             * {
             * var x = new T();
             * x.Prop1 = (cast)row["Prop1"]
             * x.Prop2 = (cast)row["Prop2"]
             * x.Prop3 = (cast)row["Prop3"]
             * x.Prop4 = (cast)row["Prop4"]
             * etc.
             * return x
             * }
             */
            var lambda = Expression.Lambda<Func<SqlDataReader, T>>(body, sqlDataReaderParameter);
    
            // cache me!
            return lambda.Compile();
    

    Haven’t tested this, so please use with care and give it a try yourself.

    I’m not sure if I got your intended usage correct…is it?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This question appeared when I recently opened a rather old driver for my raid
I know this question has appeared few times, but the things are changing really
Help me settle an argument here. Is this: SqlCommand cmd = new SqlCommand( sql
This is probably more of a check than a question, but is the following
I am looking for help to fix a problem to appeared when migrating from
my app is nearly finished but a leak has appeared. After having spent an
I know this isn't a good question to ask and I might get cursed
I have a question as the title,I wanna get the products which appeared in
Help! I have an Axis web service that is being consumed by a C#
Help me ..my page index is not working in visual studio. my page load

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.