我想创建一个这样的方法:
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");
我该如何实现这个方法?
解决方法
您可以使用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); }
然后你只需要做一些事情:
var result = database.SomeEntities.Search(x => x.SomeProp,"value");
如果你想从数据库中做到这一点,那么这取决于数据库是什么;例如,使用LINQ-to-sql,您可以添加其他方法:
static IQueryable<TSource> Search<TSource,TValue>( this System.Data.Linq.DataContext database,TValue value) where TSource : class { IQueryable<TSource> source = database.GetTable<TSource>(); return Search(source,selector,value); }
并使用:
var result = database.Search<SomeEntity,string>(x => x.SomeProp,"value");
坦率地说,我认为使用database.SomeEntities版本更清楚.