mercredi 12 juillet 2017

C# Get Method by reflection with Expression

i am new to reflection and hope you can help me out. I find a lot questions similar to mine but does not get it transmitted on my Problem.

I have a method:

IEnumerable<TEntity> Get<TEntity>(Expression<Func<TEntity, object>> propertyNameExpression, object propertyValue) where TEntity : NT.Base.Framework.ODL.Entity;

I normally call this Method like this: PersistentService.Get<Agent>(a => a.ID, Guid.Empty);

But now i know it only at run time which class i have. So i have a

Type classType;

And need to know how to call this method with the classType. I have a temporary solution, where i take the method with a string but hardcoded strings in code are not so nice.

MethodInfo methodInfo = typeof(PersistenceService).GetMethod("Get", new Type[] { classType, typeof(string) });
                    var classMethod = methodInfo.MakeGenericMethod(classType);

                    string query = "SELECT * FROM " + classType.Name + " WHERE " + classType.Name + ".Id = '" + pg.GUID.ToString() + "'";
                    dynamic dEnumeration = classMethod.Invoke(PersistenceService, new object[] { query });
                    dynamic dEntity = Enumerable.FirstOrDefault(dEnumeration);

So please help me, how to get and invoke this method.





Aucun commentaire:

Enregistrer un commentaire