Generic method to query in Entity Framework

Posted on March 24, 2009. Filed under: Entity Framework |

Here I am going to talk about the generic method and expression to query using Entity Framework. I know it’s not a big deal but I choose simple thing to share my very little knowledge (!!) about expression and entity framework.Ok, here I consider an example of querying Max value. I know it’s already in there but it’s only an approach- of how you use your own (custom) expression when you are in generic place and  you don’t know much (properties) about your entity set:

public static int GetMaxValue  <  T  >  (ObjectContext contex, string keyFieldName)
   if (null != contex)
       // First we define the parameter that we are going to use the clause.
        var param = Expression.Parameter(typeof(T), typeof(T).Name);
      // Now we’ll make our lambda function that returns the "ID" property .
       var maxExpression = Expression.Lambda< Func <  T ,int  > >(Expression.Property(param, keyFieldName), param);
       // Now I can get desire entityset from context using reflection.
      System.Data.Objects.ObjectQuery  <  T >    query = contex.GetType().GetProperties().Where(p => p.PropertyType.BaseType.Equals(typeof(System.Data.Objects.ObjectQuery)) && p.PropertyType.GetGenericArguments().First().Equals(typeof(T))).First().GetValue(contex, null) asSystem.Data.Objects.ObjectQuery <  T > ;
         if (null != query)
                int? i = query.Max <  T ,  int >(maxExpression);
                if (i.HasValue)
                return i.Value;                  
       catch (Exception){}
     return 0;

You can create your own expression in place of “maxExpression” . Now how do you call this generic method from generic place.lets consider that you want to get the Max of entity-key(Primary key) of an entity-set(Table) and set the (Max + 1) in your new entity object that is going to be added in database.Using reflection you can get the property name/names of Entity key

IEnumerable<PropertyInfo> keyProperties = entity.GetType().GetProperties().
    Where(p => ((EdmScalarPropertyAttribute[])p.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false)).Any(a => a.EntityKeyProperty == true));

If you have composite primary key then  value of “keyProperties” will be greater than one. For making our  example very simple I assume that here is no composite key here and the datatype of entity key is integer.

PropertyInfo item = keyProperties[0];
//type generic method 
Type typeofClass = typeof(ClassOfGenericMethod);

//take the specific static method 
MethodInfo methodInfo = typeofClass.GetMethod("GetMaxValue", BindingFlags.Public);

// Binding the method info to generic arguments 
Type[] genericArguments = new Type[] { entity.GetType() };
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(genericArguments);
// Invoke the method and passing parameters 
// The null parameter is the object to call the method from.if it is static, pass null. 
object returnValue = genericMethodInfo.Invoke(null, new object[] { context, item.Name });
//set max value  
item.SetValue(entity, (long)result + 1, null); 

Here I call the “GetMaxValue” and set its value by incease of one to entity-key Property of target object. Anyways Sorry for my bad english.

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

5 Responses to “Generic method to query in Entity Framework”

RSS Feed for Morshed Anwar's Blog Comments RSS Feed


Thanx, for the great article.
How can we get the max value for another integer field other than identity field?

Friendly greetings,

Thank you so much Pieter for your comment and interest. You can see that here I simply use the reflection here to Identify the primary key with help of Custom attribute. But field other than Primary key is not something Unique,You can’t get that using custom attribute. You need something to identify that property. For this You can send the field name as a parameter and Get the Property info Using Reflection. You can also make your custom attribute to identify your desired entity property. All these depend on how have designed your application , Just try to make as much as simple.

I correctly landed at a very nice article through which I have completed my task simple.
Thank you for sharing Morshed.

My pleasure… and Its an honor if you find these helpful. Thanx for reading.

When I Created this with the same code I got error


After executing Where(p => p.PropertyType.BaseType.Equals(typeof(System.Data.Objects.ObjectQuery)) && p.PropertyType.GetGenericArguments().First().Equals(typeof(T))).First().GetValue(contex, null) as System.Data.Objects.ObjectQuery

five times I got the error please help me

Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: