[英]Entity Framework Core LINQ query with multiple where clauses
我的项目需要一些示例代码。 我正在使用 EF CORE 2.1.1。
我创建了一个接受 3 个参数的函数,在该函数中我正在执行一个 LINQ(lambda 表达式查询),返回一个列表。
这是我的功能:
public IEnumerable<Donneesource> GetAllSourcesFromBDD(DateTime PremierDateCom, DateTime DerniereDateCom, string Secteur)
{
try
{
//Récupération des données.
IEnumerable<Donneesource> RawDatas = _sourceDAL.Donneesource
.Where(ic => ic.EstCopieDestination == false)
.Where(s => PremierDateCom != DateTime.MinValue && s.SComPremierDate.Value.Date == PremierDateCom.Date)
.Where(s => DerniereDateCom != DateTime.MinValue && s.SComDerniereDate.Value.Date == DerniereDateCom.Date)
.Where(s => Secteur != string.Empty && s.SSectNom == Secteur)
.ToList();
return RawDatas;
}
catch(Exception)
{
return null;
}
}
默认情况下,我将 DateTime 参数设置为 DateTime.MinValue (PremierDateCom,DerniereDateCom),将字符串参数设置为 string.Empty (Secteur)。
我正在尝试使用 where 子句创建单个查询。 我想忽略带有默认参数的 where 子句。 例如,如果 PremierDateCom = DateTime.MinValue(或其他参数),那么如果我想在查询中包含 where 子句,我想忽略 where 子句。
我不想创建这样的查询:
//Filtre
if (PremierDateCom != DateTime.MinValue)
RawDatas = RawDatas.Where(x => x.SComPremierDate.Value.ToShortDateString() == PremierDateCom.ToShortDateString());
//Filtre
if (DerniereDateCom != DateTime.MinValue)
RawDatas = RawDatas.Where(x => x.SComDerniereDate.Value.ToShortDateString() == DerniereDateCom.ToShortDateString());
//Filtre
if (Secteur != null)
RawDatas = RawDatas.Where(x => x.SSectNom == Secteur);
假设_sourceDAL.Donneesource
为您提供IQueryable<T>
那么您应该通过Where
if
语句中添加Where
子句来构建您的查询。 这是因为IQueryable
在您实现它之前不会对数据库运行查询,即使用foreach
或.ToList()
。 所以像这样:
IQueryable<Donneesource> RawDatas = _sourceDAL.Donneesource
.Where(ic => ic.EstCopieDestination == false)
.Where(s => PremierDateCom != DateTime.MinValue && s.SComPremierDate.Value.Date == PremierDateCom.Date)
.Where(s => DerniereDateCom != DateTime.MinValue && s.SComDerniereDate.Value.Date == DerniereDateCom.Date)
.Where(s => Secteur != string.Empty && s.SSectNom == Secteur);
if (PremierDateCom != DateTime.MinValue)
{
RawDatas = RawDatas.Where(x => x.SComPremierDate.Value.ToShortDateString() == PremierDateCom.ToShortDateString());
}
if (DerniereDateCom != DateTime.MinValue)
{
RawDatas = RawDatas.Where(x => x.SComDerniereDate.Value.ToShortDateString() == DerniereDateCom.ToShortDateString());
}
if (Secteur != null)
{
RawDatas = RawDatas.Where(x => x.SSectNom == Secteur);
}
//Now get the data from the database:
return RawDatas.ToList();
为了避免使用许多if
语句,您还可以尝试以下操作:
IQueryable<Donneesource> RawDatas = _sourceDAL.Donneesource
.Where(ic => !ic.EstCopieDestination)
.Where(s => PremierDateCom != DateTime.MinValue ? s.SComPremierDate.Value.Date == PremierDateCom.Date : true)
.Where(s => DerniereDateCom != DateTime.MinValue ? s.SComDerniereDate.Value.Date == DerniereDateCom.Date : true)
.Where(s => Secteur != string.Empty ? s.SSectNom == Secteur : true);
您可以使用条件语句,如果不满足条件,则改为传递true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.