C# 发送列表<;T>;作为ASP.NET核心Web Api中帖子正文中的可选参数
我有一个模型,它为post请求主体采用可选参数:C# 发送列表<;T>;作为ASP.NET核心Web Api中帖子正文中的可选参数,c#,asp.net-core,asp.net-web-api,dbcontext,C#,Asp.net Core,Asp.net Web Api,Dbcontext,我有一个模型,它为post请求主体采用可选参数: public class ReportFilterModel { public int? ReportStatusId { get; set; } public Guid? AreaID { get; set; } } 这将根据用户提供的过滤器在DB中进行搜索: var report = _context.tbl_Reports.AsQueryable(); if (model.Repor
public class ReportFilterModel
{
public int? ReportStatusId { get; set; }
public Guid? AreaID { get; set; }
}
这将根据用户提供的过滤器在DB中进行搜索:
var report = _context.tbl_Reports.AsQueryable();
if (model.ReportStatusId.IsNotNull())
report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);
if (model.Area.IsNotNull())
report = report.Where(x => x.IsDeleted == false && x.Area.Id == model.AreaId);
然后它最终会返回这个:
finalReports = await report
.Where(x => x.IsDeleted == false)
.Select(x => new ReportsWithFiltersModel
{
Id = x.Id,
Area = Id,
UserId = x.UserId,
ReportStatus = x.ReportStatusId.GetEnumDescription(),
}).ToListAsync();
所有这些工作都非常好,但现在我想给出一个可选参数列表,如下所示:
public class ReportFilterModel
{
public List<int>? ReportStatusId { get; set; }
public List<Guid>? AreaID { get; set; }
}
公共类ReportFilterModel
{
公共列表?ReportStatusId{get;set;}
公共列表?AreaID{get;set;}
}
这是一个例外
'List<int>' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'List<int>' could be found (are you missing a using directive or an assembly reference?)
“List”不包含“Value”的定义,并且找不到接受“List”类型的第一个参数的可访问扩展方法“Value”(是否缺少using指令或程序集引用?)
如何修复此问题??不代表可选。它意味着可以为null,其中T是值类型(它应用于值类型并使它们可以为null) 引用类型(如列表)已经可以为空
List<int> x = null; //valid version of what you are trying to achieve with List<int>?
int? or Nullable<int> //valid
List<int?> x or List<Nullable<int>> ; //valid
List x=null//您试图通过列表实现的目标的有效版本?
智力?或可空//有效
列表x或列表//有效的
您正在混合两个概念和(在C#8.0中添加)。用?
标记的Nullable值类型基本上是的快捷方式,它们具有属性<代码>列表(在您的情况下是列表
和列表
)是引用类型,并且它没有值
属性,并将其标记为?
使编译器知道此属性可以包含null
引用,并使其能够强制执行规则,以确保您已正确检查此属性的null引用。简而言之,你的列表?ReportStatusId
和列表?AreaID
已经是“可选的”,并且?
使编译器知道这一点
想修吗
改变
if (model.ReportStatusId.IsNotNull())
report = report.Where(x => x.IsDeleted == false && x.ReportStatusId == (StatusEnum)model.ReportStatusId.Value);
到
if(model.ReportStatusId.IsNotNull()&&model.ReportStatusId.Any())
var statuses=model.ReportStatusId.Cast().ToList();
report=report.Where(x=>x.IsDeleted==false&&statuses.Contains(x.ReportStatusId));
您忘记了C#8功能
if (model.ReportStatusId.IsNotNull() && model.ReportStatusId.Any())
var statuses = model.ReportStatusId.Cast<StatusEnum>().ToList();
report = report.Where(x => x.IsDeleted == false && statuses.Contains(x.ReportStatusId));