首页 > 解决方案 > 在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 查询中执行此操作?

标签: c#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您只会得到那些命名的用户,该项目类型在项目列表中的某处..等


推荐阅读