C# 当主键列返回null,因此相关属性为null时,如何使用select运行linq查询

C# 当主键列返回null,因此相关属性为null时,如何使用select运行linq查询,c#,entity-framework,linq,C#,Entity Framework,Linq,我有以下疑问: var ComplaintsQuery = _context.TblComplaints.Select(p => new { ComplaintId = p.ComplaintId, ClientId = p.ClientId, ClientFullName = p.Client.ClientFullName, Datecomplaintreceived = p.Datecomplaintrec

我有以下疑问:

    var ComplaintsQuery = _context.TblComplaints.Select(p => new
    {
        ComplaintId = p.ComplaintId,
        ClientId = p.ClientId,
        ClientFullName = p.Client.ClientFullName,
        Datecomplaintreceived = p.Datecomplaintreceived,
        StaffmemberId = p.StaffmemberId,
        StaffFullName = p.Staffmember.StaffFullName,
    }
    )?.AsQueryable();
投诉的数据库表在某些行中,
clientId
为空,因此我无法检索
ClientFullName
,类似于
StaffFullname
StaffmemberId

有没有办法让查询返回null而不是一个破坏代码的null异常?

试试看

var ComplaintsQuery = (from p in _context.TblComplaints
                               select new
                               {
                                   ComplaintId = p.ComplaintId,
                                   ClientId = p.ClientId,
                                   ClientFullName = p.ClientId == null ? null : p.Client.ClientFullName,
                                   Datecomplaintreceived = p.Datecomplaintreceived,
                                   StaffmemberId = p.StaffmemberId,
                                   StaffFullName = p.Staffmember == null ? null : p.Staffmember.StaffFullName,
                               }).AsQueryable();

感谢Jon Skeet的评论,下面的代码可以正常运行,没有空异常输出

        var ComplaintsQuery = _context.TblComplaints.Select(p => new
        {
            ComplaintId = p.ComplaintId,
            ClientId = p.ClientId,
            ClientFullName = p.ClientId == null ? null : p.Client.ClientFullName,
            Datecomplaintreceived = p.Datecomplaintreceived,
            StaffmemberId = p.StaffmemberId,
            StaffFullName = p.StaffmemberId == null ? null : p.Staffmember.StaffFullName,
        }
        )?.AsQueryable();

如果您使用EntityFramework核心,它不会在
null
上给您带来异常,但是如果您使用EntityFramework,您应该在预期的
null
对象之后使用
Client
StaffMember
而不是整个查询

var ComplaintsQuery = _context.TblComplaints.Select(p => new
    {
        ComplaintId = p.ComplaintId,
        ClientId = p.ClientId,
        ClientFullName = p.Client?.ClientFullName,
        Datecomplaintreceived = p.Datecomplaintreceived,
        StaffmemberId = p.StaffmemberId,
        StaffFullName = p.Staffmember?.StaffFullName,
    }
    ).AsQueryable();

您是否尝试过使用
p.ClientId==null?null:p.Client.ClientFullName
p.Client?.FullName
?(我似乎记得后者在某一点上不受支持,但现在可能是…)如果您直接针对
\u上下文进行查询。TBLCompaints
这些空检查应该是不必要的,因为查询已转换为SQL。如果您确实需要它们,您就不会显示实际的代码。同样地,
?.AsQueryable()不是必需的。始终避免冗余代码。