如何阅读表达式';的内容
本文关键字:何阅读 表达式 | 更新日期: 2023-09-27 18:26:53
我有一个类,它可以作为某种存储库工作,并授予对数据库的访问权限。我正在尝试对其进行自定义,以允许使用表达式进行查询。
所以,我希望能够做到这一点:
IList<MyClass> myList = myRepository.GetBy(x => x.Name == "SomeName");
//and...
IList<MyClass> myList2 = myRepository.GetBy(x => x.Name == "SomeName" && x.ID = 5);
这就是我需要的存储库功能:
public IList<T> GetBy(Expression<Func<T, bool>> expression)
{
//Set up the query, etc
//I'm at the WHERE clause, and I need to get the property(ies) name(s) of the expression and their values to properly set the WHERE
}
我该怎么做?
您想要做的是:IList <MyClass> myList2 = myRepository.GetBy (x => x.Name == "SomeName" && x.ID
=5);确实,您可以代表x => x.Name == "SomeName" && x.ID = 5 with Expression <Func <T, bool >>
而且还包括您仅可以对代表CCD_ 3执行的操作。
无论采用哪种方法,数据都将始终来自IEnumerable <T>
,因此始终使用Where
方法(无论何时使用命名空间System.Linq
),该方法接受委托Func <T, bool>
作为参数。如果对象IEnumerable <T>
是DbSet <T>
,这将负责在sql查询中转换委托Func <T, bool>
。请记住,只有在使用了查询数据或与方法ToList ()
或ToArray ()
一致时,才会执行正在使用的Linq查询。
示例:IEnumerable <MyClass> list = ...
从任何地方获取数据,甚至从EntityFramework 的DbSet
var query = list.Where (x => x.Name == "SomeName" && x.ID = 5);
查询是一个shost查询,在完成之前,它不包含任何数据
foreach (var x in list) is being consumed, so the query is executed
{
var c = x.Name;
}
或者这个
`var temp = query.ToList ();`
该力存储在List <MyClass>
中有了这些,我想说的是,如果您使用EntityFramework的DbSet,那么会将委托Func <T, bool>
转换为sql查询,因此数据管理器负责过滤数据(应该是这样)。仅从这一点,你就必须简单地拥有你的方法
public IList <T> GetBy (Func <T, bool> expression)
{
origen.Where (expression).ToList();
}
如果我正确理解您的问题,您应该从基本通用存储库接口继承存储库接口。
public interface IRepositoryBase<TEntity>
{
IList<TEntity> GetBy(Expression<Func<TEntity, bool>> expression)
}
从基本存储库实现实现存储库
public abstract class RepositoryBase<TEntity>: IRepositoryBase<TEntity>
{
public MyEntities EntitiesContext { get; set; }
public IList<TEntity> GetBy(Expression<Func<TEntity, bool>> expression)
{
return EntitiesContext.Set<TEntity>().Where(filter).ToList()
}
}