首页 > 解决方案 > 具有多个 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);

标签: c#linqentity-framework-core

解决方案


假设_sourceDAL.Donneesource给你一个那么你应该通过在语句中添加子句IQueryable<T>来构建你的查询。这是因为 an不会对数据库运行查询,直到您实现它,即使用 a或 a 。所以是这样的:WhereifIQueryableforeach.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();

推荐阅读