启用Nullable Reference Types时的C#匿名类型警告



我使用的是启用了Nullable Reference Type的.net 6,当我使用匿名类型来获取LINQ查询的结果时,我会得到一个警告客户端在此不为null。CS8619:类型<匿名类型:int ContractId,string Name,string Street>与类型<匿名类型:int ContractId,string Name,string?街道>

这是我的代码:

var contracts = _dbContext.Contracts.Select(
c => new
{
c.ContractId,
c.Client.Name,
c.Client.Street
}
).Where(c => c.ContractId == contractId).Take(9).ToList();

进行查询和避免警告的正确方法是什么?

试试这个:

var contracts = _dbContext.Contracts
.Include(x => x.Client) // Include clients
.Where(c => c.ContractId == contractId)
.Select(c => new
{
c.ContractId,
Name = c.Client == null ? null : c.Client.Name, // nullable check and line up namings of properties 
Street = c.Client == null ? null : c.Client.Street // nullable
})
.Take(9)
.ToList();

如果ClientId[Required],则看起来Client不可能是null,唯一缺少的可能是子查询.Include(x => x.Client)

铸造到(string?)可以解决问题,即

var contracts = _dbContext.Contracts.Select(
c => new
{
c.ContractId,
c.Client.Name,
Street = (string?)c.Client.Street
}
).Where(c => c.ContractId == contractId).Take(9).ToList();

最新更新