我尝试了几种可能性,并对 stackoverflow 上的博客和答案进行了适当的研究。可能是我,但我就是无法让这个动态 linq 查询工作。
我在 Web Api 项目上有一个 Controller ,定义了以下投影和路线。
private static readonly Expression<Func<Company, CompanyLightListDTO>> AsCompanyLightListDTO = x => new CompanyLightListDTO
{
Name = x.Name,
Id = x.Id
};
[Route("Test")]
[ResponseType(typeof(CompanyLightListDTO))]
public IQueryable<CompanyLightListDTO> GetTest(string name=null, string
email=null, bool? isSupplier=null, bool? isCustomer=null)
{
IQueryable<Company> query = db.Companies;
if (!String.IsNullOrEmpty(name))
query.Where(c => c.Name.Contains(name));
if (!String.IsNullOrEmpty(email))
query.Where(c => c.Email.Contains(email));
if (isSupplier.HasValue)
query.Where(c => c.isSupplier.Equals(isSupplier));
if (isCustomer.HasValue)
query.Where(c => c.isCustomer.Equals(isCustomer));
// Return ??
}
我已经尝试过多次返回。它们都忽略前面的所有 where.() 并返回所有公司。
not working because return all companies. The Where clauses are not applied
return query.Include(c => c.Name).Select(AsCompanyLightListDTO);
return query.Select(AsCompanyLightListDTO);
我唯一能让这个方法发挥作用的就是这样做
return db.Companies.Include(c => c.Name)
.Where(c => c.Name.Contains(name)
&& c.Email.Contains(email)
&& c.isSupplier.Equals(isSupplier)
&& c.isCustomer.Equals(isCustomer))
.Select(AsCompanyLightListDTO);
但我想要一个动态 linq 查询,以便我可以执行这些类型的调用:
api/Companies/Test/name=somename&isCustomer=True api/Companies/Test/isCustomer=True&isSupplier=True api/Companies/Test/name=somename&email=someemail
有任何高尚的开发人员愿意帮助新的编码员吗?
最诚挚的问候 德威尔逊
最佳答案
您是否尝试将 GetTest
替换为此?
IQueryable<Company> query = db.Companies;
if (!String.IsNullOrEmpty(name))
query = query.Where(c => c.Name.Contains(name));
if (!String.IsNullOrEmpty(email))
query = query.Where(c => c.Email.Contains(email));
if (isSupplier.HasValue)
query = query.Where(c => c.isSupplier.Equals(isSupplier));
if (isCustomer.HasValue)
query = query.Where(c => c.isCustomer.Equals(isCustomer));
Queryable
方法(Select
、Where
等)返回新的 IQueryable
实例。
关于c# - 动态 Linq 不起作用 - 选择未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36017834/