【问题标题】:Entity Framework Search for Enum pulls back all dataEnum 的实体框架搜索拉回所有数据
【发布时间】:2015-06-10 11:29:50
【问题描述】:

我正在使用实体框架执行以下查询,我想通过TakerStatus(即Enum)过滤我的结果:

var takerCount = this.DbContext.Set<Quiz>().Single(x => x.UrlId == urlId).Takers.Count(x => x.TakerStatus == TakerStatus.Abandoned || x.TakerStatus == TakerStatus.Complete)

这是enum

public enum TakerStatus
{
    /// <summary>
    /// Taker is currently in the process of completing the quiz
    /// </summary>
    InProgess = 0,

    /// <summary>
    /// Taker failed to complete the quiz and was marked as abandoned
    /// </summary>
    Abandoned = 1,

    /// <summary>
    /// Taker successfully completed taking the quiz
    /// </summary>
    Complete = 2
}

我意识到这个查询运行缓慢,我想知道为什么,那里有很多记录,但我想通过添加索引来提高速度。

但是在检查了这个实际产生的查询之后,我发现它似乎忽略了 lambda 表达式......

SELECT
`Extent1`.`Id`, 
`Extent1`.`QuizId`, 
`Extent1`.`QuizVersionId`, 
`Extent1`.`UserId`, 
`Extent1`.`TakerName`, 
`Extent1`.`CurrentQuestionNumber`, 
`Extent1`.`CurrentQuestionStartTime`, 
`Extent1`.`CurrentScore`, 
`Extent1`.`Completed`, 
`Extent1`.`IpAddress`, 
`Extent1`.`StartTime`, 
`Extent1`.`FinishTime`, 
`Extent1`.`Abandoned`, 
`Extent1`.`PasswordId`, 
`Extent1`.`PersonalityResultId`, 
`Extent1`.`PercentageResult`, 
`Extent1`.`Status`, 
`Extent1`.`TakerStatus`
FROM `Taker` AS `Extent1`
 WHERE `Extent1`.`QuizId` = 330

它为测验选择了每个考生,但甚至没有检查TakerStatus 列。

什么给了?我想在TakerStatus 中添加索引以加快速度

【问题讨论】:

    标签: c# mysql entity-framework enums ef-code-first


    【解决方案1】:

    试试这个,我猜它需要一对围绕条件的大括号。我认为这是一个运算符优先级问题。

    var takerCount = this.DbContext.Set<Quiz>().Single(x => x.UrlId == urlId).Takers.Count(x => (x.TakerStatus == TakerStatus.Abandoned || x.TakerStatus == TakerStatus.Complete))
    

    【讨论】:

      【解决方案2】:

      Single 枚举您的IQueryable 并触发查询(其余处理在应用程序服务器内存中完成,在整个结果集上)

      我会尝试:

      var takerCount = this.DbContext
          .Set<Quiz>()
          .Where(x => x.UrlId == urlId)
          .Select(o=>o.Takers.Count(x => x.TakerStatus == TakerStatus.Abandoned || x.TakerStatus == TakerStatus.Complete))
          .FirstOrDefault();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多