How to implement a method with a C # expression parameter

I want to create a method like this:

var result = database.Search<EntityType>(x=>x.Name, "Entity Name field value"); result = database.Search<EntityType>(x=>x.Id, "Entity Id field value"); result = database.Search<EntityType2>(x=>x.Id, "Entity2 Id field value"); result = database.Search<EntityTypeAny>(x=>x.FieldAny, "EntityAny FieldAny value"); 

How can I implement this method?

+6
source share
3 answers

You can include the selector and value in the predicate using Expression.Equal :

 static IQueryable<TSource> Search<TSource, TValue>( this IQueryable<TSource> source, Expression<Func<TSource,TValue>> selector, TValue value) { var predicate = Expression.Lambda<Func<TSource,bool>>( Expression.Equal( selector.Body, Expression.Constant(value, typeof(TValue)) ), selector.Parameters); return source.Where(predicate); } 

Then you just need to do something like:

 var result = database.SomeEntities.Search(x => x.SomeProp, "value"); 

If you want to do this from a database, it depends on what the database is; for example, with LINQ-to-SQL you can add an additional method:

 static IQueryable<TSource> Search<TSource, TValue>( this System.Data.Linq.DataContext database, Expression<Func<TSource, TValue>> selector, TValue value) where TSource : class { IQueryable<TSource> source = database.GetTable<TSource>(); return Search(source, selector, value); } 

and use:

 var result = database.Search<SomeEntity, string>(x => x.SomeProp, "value"); 

frankly, I think it’s more understandable to use the version of database.SomeEntities .

+9
source

I can only think about it (with two general arguments)

  public static IEnumerable<TModel> Search<TModel, TValue>( Expression<Func<TModel, TValue>> expression, TValue value ) { return new List<TModel>(); } 

Using

 var result = Search<EntityType, int>(x => x.Id, 1); var result2 = Search<EntityType, string>(x => x.Name, "The name"); 

you can replace TValue with an object to avoid a second general argument, but I would stick with that.

Btw. this works great with this little helper

 public static class ExpressionHelpers { public static string MemberName<T, V>(this Expression<Func<T, V>> expression) { var memberExpression = expression.Body as MemberExpression; if (memberExpression == null) throw new InvalidOperationException("Expression must be a member expression"); return memberExpression.Member.Name; } } 

Now you can get the Property Name (Id other Name) in this example by calling

 var name = expression.MemberName(); 
+1
source

You want the types to be dynamic

 public ReturnType Read<ReturnType>(string FieldName, object dfVal) { if (Res.IsDBNull(Res.GetOrdinal(FieldName))) return dfVal; try { return (ReturnType)Res.GetValue(Res.GetOrdinal(FieldName)); } catch (Exception ex) { return dfVal; } } 
0
source

Source: https://habr.com/ru/post/944503/


All Articles