【问题标题】:How can I use a nullable list where in linq in Entity Framework code first?如何首先在实体框架代码中的 linq 中使用可空列表?
【发布时间】:2017-05-13 15:46:19
【问题描述】:

我在过滤表中的状态列时遇到问题:

public class QuestionInfo
{
    [Key]
    public int Id { get; set; }
    public string Content { get; set; }
    public QuestionStatus Status { get; set; }
}

public enum QuestionStatus : byte
{
    None = 0,
    NeedEdit = 1,
    Blocked = 2,
    Accepted = 3,
    Checking = 4
}

我想通过可以为空的状态列表过滤我的问题,当filterList 为空时,我想全选例如:

List<QuestionStatus> filterList = new List<QuestionStatus>();

var questions = (from x in context.QuestionInfoes 
                 where filterList?.Contains(x.Status) 
                    && x.Score > 10 select x).ToList();

或:

var questions = (from x in context.QuestionInfoes 
                 where (filterList == null ? true : filterList.Contains(x.Status))
                    && x.Score > 10 select x).ToList();

我在查询一中得到这个语法错误:

C# - 不能隐式转换 bool 类型?

我从查询二中得到这个错误:

System.NotSupportedException:无法创建类型为 'System.Collections.Generic.List`1[[Atitec.OffseeAPI.DataBase.Models.Games.QuestionsOfKing.QuestionStatus, Atitec.OffseeAPI.DataBase, Version= 的空常量值1.0.0.0,文化=中性,PublicKeyToken=null]]'。
此上下文仅支持实体类型、枚举类型或原始类型。

【问题讨论】:

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


    【解决方案1】:

    如何在 linq 中首先在实体框架代码中使用可空列表?

    正如您已经发现的那样,您不能(不支持例外)。

    解决方法是使用条件Where:

    var query = context.QuestionInfoes.Where(x => x.Score > 10);
    if (filterList != null)
        query = query.Where(x => filterList.Contains(x.Status));
    var result = query.ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-29
      • 2011-06-24
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多