c# - 在linq c#中使用参数搜索查询
问题描述
我需要在 net core 3.0 中使用动态参数构建搜索查询。
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
我想添加搜索参数,如用户名、项目类型、汽车型号和用户数据。我尝试在“选择新 UserDto”之前添加“位置”,但并非总是用户会提供所有搜索参数。如果我在下面给出:
if(fromSearch.UserName != null && fromSearch.UserName.Lenght > 0)
{
query = query.Where(u => u.Name == fromSearch.UserName);
}
它有效(在 user.data 上无效)但它正确吗?如何在 linq 查询中执行此操作?
解决方案
做这样的事情:
IQueryable<UserDto> query =
from user in dbContext.DB_USER
join items in dbContext.DB__ITEMS on user.IdItem equals items.IdItem
join cars in dbContext.DB_CARS on user.IdCars equals cars.IdItem
join statsCar in dbContext.DB_STATS_CARS on cars.IdCars equals statsCar.Id;
select new UserDto
{
Id = user.Id,
Name = user.Name,
Data = user.Data.HasValue ? user.Data.Value.ToUnixTime() : default(long?),
Lvl = user.L,
Items = new ItemsUdo
{
Id = items.Id,
Type = items.Type,
Value = items.Value
},
Cars = new CarsDto
{
Id = cars.Id,
Model = cars.model,
Color = cars.Color
}
};
if(!string.IsNullOrWhitespace(username))
query = query.Where(ud => ud.Name == username);
if(!string.IsNullOrWhitespace(itemtype))
query = query.Where(ud => ud.Items.Any(i => i.Type == itemtype));
if(!string.IsNullOrWhitespace(carmodel))
query = query.Where(ud => ud.Cars.Any(c => c.Model == carmodel));
等等。这些将像 AND 一样工作;如果您指定 ausername
和 anitemtype
您只会得到那些命名的用户,该项目类型在项目列表中的某处..等
推荐阅读
- .net - .NET 5 (Core) MVC - 使用 en-GB 的模型绑定 DateTime 不能在 GET 上工作,但在 POST 上工作正常
- identityserver4 - IdentityServer4 客户端凭据性能
- c++ - 如何在 LLVM 8.0 之后使用 getOrinsertfunction 方法
- python - 检查熊猫数据框列(具有列表作为值)是否具有另一个列表的一个元素
- reactjs - 使用材料UI和nextjs的反应项目中的Jss autoprefixer
- c - 使用C中的堆栈获取迷宫的出口
- javascript - 如果访问者允许 cookie,是否可以找到访问者的电子邮件地址?
- visual-studio-code - 从 vscode 启动容器时无法连接到“workspaceMount”
- django - Django_Tables2 访问器/相关字段
- spring - @Value 注释是否检测到它注入的属性(在属性文件中)的更改