c# - 具有多个 where 子句的 Entity Framework Core LINQ 查询
问题描述
我的项目需要一些示例代码。我正在使用 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>
来构建你的查询。这是因为 an不会对数据库运行查询,直到您实现它,即使用 a或 a 。所以是这样的:Where
if
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();
推荐阅读
- asp.net - 将数据库上的更改保存为历史数据
- image - 将文本包裹在图像顶部的 C# 代码 - OpenXml
- java - IntelliJ 重构为内联冗余数据类
- java - 如何在 Java 中连接 CloudFront?
- javascript - 我单击了我的彩色按钮图像,但它们没有出现在控制台的数组中
- reactjs - Axios 获取请求不起作用,但发布请求起作用?
- webpack - (多错误)找不到模块:错误:无法解析“babel/loader”
- c - 使用 SAR ADC 进行相位角测量
- python - 运行随机森林分类器时出错
- sqlite - system.missingmethodexception: '方法未找到:void sqlite.sqliteconnection..ctor(string,sqlite.sqliteopenflags,bool,object)'