【问题标题】:Enum defined as IsOptional cannot be queried for null values定义为 IsOptional 的枚举无法查询空值
【发布时间】:2015-06-18 22:29:11
【问题描述】:

我已通过 Fluent API 将实体上的 Enum 属性定义为 IsOptional。数据库反映 IsOptional,因为它显示为可为空的类型。当我尝试查询此 Entity 属性以获取空值时,我收到以下错误:

The 'UserType' property on 'Group' could not be set to a 'null' value. 
You must set this property to a non-null value of type 'UserType'.

查询如下:

var groups = (from g in db.Groups
              let reqs = from r in db.Requests 
              where r.Id == requestId from gg in r.Groups select gg.Id                                  
              where g.ContentArea.Id == db.Requests.FirstOrDefault(o => o.Id == requestId).ContentArea.Id
              where !reqs.Contains(g.Id)
              where (g.UserType == db.Requests.FirstOrDefault(r => r.Id == requestId).User.UserType || g.UserType == (UserType?)null)
              select g).ToList();

而特别中断的部分是在 OR 语句之后

g.UserType == (UserType?)null

我尝试将 g.UserType 与 null 进行比较,设置 UserType 的实例? nullType = null 并进行了比较,但似乎没有任何效果。这似乎是EF的一个缺点。有什么建议吗?

编辑:按要求包含整个查询。

【问题讨论】:

  • 请显示完整的查询,我认为问题出在它的另一部分。
  • 我认为UserType 在数据库中是可以为空的,而不是在类中。
  • @GertArnold 你是对的。我将其定义为 UserType?它奏效了。回复一个答案,这样我就可以给你信用。

标签: c# ef-code-first entity-framework-6 ef-fluent-api


【解决方案1】:

问题不在于语句的结构,而在于 EF 试图实现的实体。 Group 具有不可为空的属性 UserType。但是在数据库中它是可以为空的,并且一些返回的记录有它的空值。

所以你要么必须使属性为空:

UserType? UserType { get; set; }

或确保语句不返回空值。

【讨论】:

    猜你喜欢
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    相关资源
    最近更新 更多