在EF core 2.1投影中的三元运算符中运行时,值不能为null异常



实际上,我有一些问题,不能为可为null的字段设置null值而不是默认值。

我无法在select语句中使用EF core 2.1编写正确的代码,因为我面临运行时异常"值不能为null",或者不可能使用null传播运算符。

注意:如果它很重要,则从查询中的子实体中提取行。

VotedAt = i.CurrentUserVote == null 
? new DateTimeOffset() 
: i.CurrentUserVote.VotedAt,
CurrentUserVote = i.CurrentUserVote == null 
? false 
: i.CurrentUserVote.IsPositive,

我想写:

VotedAt = i.CurrentUserVote == null 
? null 
: i.CurrentUserVote.VotedAt,
CurrentUserVote = i.CurrentUserVote == null 
? null 
: i.CurrentUserVote.IsPositive,

甚至:

VotedAt = i.CurrentUserVote?.VotedAt,
CurrentUserVote = i.CurrentUserVote?.IsPositive,

社区要求的其他信息:所选实体:

public class IssueListItem
{
public int Id { get; set; }
public string Title { get; set; }
public Votes Votes { get; set; }
}
public class Votes
{
public int Positive { get; set; }
public int Negative { get; set; }
public int All { get; set; }
public bool? CurrentUserVote { get; set; }
public DateTimeOffset? VotedAt { get; set; }
}

选择:

return _unitOfWork.Issues.GetQuery()
.Filter(query.Filter)
.WithVotes<Issue, IssueVote, int>(currentUserId)
.Order(query.Sorter)
.Select(i => new IssueListItem
{
Id = i.Item.Id,
Votes = i.Votes,
Title = i.Item.Title,
//removed some other properties
})
.ToListAsync();

其中WithVotes<Issue, IssueVote, int>(currentUserId)为:

return q
.Select(i => new
{
Item = i,
VoutesGroups = i.Votes
.GroupBy(v => v.IsPositive, v => true, (key, vg) => new { IsPositive = key, Count = vg.Count() }),
CurrentUserVote = currentUserId == null ? null : i.Votes.FirstOrDefault(v => v.CreatedById == currentUserId),
})
.Select(i => new AssignVotesModel<TEntity, TVote, TId>
{
Item = i.Item,
Votes = new Votes
{
Positive = i.VoutesGroups.Where(vg => vg.IsPositive == true).Sum(vg => vg.Count),
Negative = i.VoutesGroups.Where(vg => vg.IsPositive == false).Sum(vg => vg.Count),
All = i.VoutesGroups.Sum(vg => vg.Count),
VotedAt = i.CurrentUserVote == null ? new DateTimeOffset() : i.CurrentUserVote.VotedAt,
CurrentUserVote = i.CurrentUserVote == null ? false : i.CurrentUserVote.IsPositive,
}
});

在数据库或实体映射中定义的列可能不能为null。

请检查实体模型是否没有Required属性。还要检查指定的属性是否未在modelBuilder配置中使用Required进行标记。

最后,从RDBMS中检查表列是否设置为IS NOT NULL

相关内容

  • 没有找到相关文章

最新更新