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

时间:2019-01-25 12:04:11

标签: c# ef-core-2.2

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

我无法在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,
                    }
                });

1 个答案:

答案 0 :(得分:0)

在数据库或您的实体Mapping中,定义的列可能不能为null。

检查您的实体模型没有Required属性。另外,请检查在Required配置中指定的属性是否未标记有modelBuilder

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