【问题标题】:Get Data Based on Filter(Not Mandatory Fields) Using Entity Framework使用实体框架根据过滤器(非必填字段)获取数据
【发布时间】:2020-02-11 09:57:41
【问题描述】:

我需要从名为Student 的实体中获取数据,该实体具有字段(Id、Name、Age、Dob)。我有一个请求对象StudentFilter

public class StudentFilter 
{
      public int? Id {get;set;}
      public string Name {get;set;}
      public int Age {get;set;}
      public DateTime Dob {get;set;}
}

现在基于此,我需要使用这些过滤器形成一个查询并从数据库中获取数据:

public List<Student> Get(StudentFilter  request)
{
     if(request.Id.HasValue && request.Id > 0)
     {
     }

     if(request.Age.HasValue && request.Age > 0)
     {
     }

     if(request.Dob.HasValue)
     {
     }

     _context.<Student>.Get()
}

有人可以帮我吗?在此先感谢

【问题讨论】:

  • 到目前为止您尝试过什么?您是否遇到了具体问题?
  • 添加了答案

标签: c# entity-framework entity-framework-core linq-to-entities


【解决方案1】:

试试这个,根据你的情况链接.Where

var query = context.Students.AsQueryable();

if(request.Id.HasValue && request.Id > 0)
{
    //equal query
    query = query.Where(x => x.Id == request.Id.Value);
    /* greater than or less than and equal to query
    *query = query.Where(x => x.Id >= request.Id.Value) or query.Where(x => x.Id <= request.Id.Value) or query.Where(x => x.Id != request.Id.Value)
    */
}

if(request.Age.HasValue && request.Age > 0)
{
    query = query.Where(x => x.Id == request.Age.Value);
    //same applies to top depending on your condition, can be !=, <=, >= or between (< && >)
}

if(request.Dob.HasValue)
{
    query = query.Where(x => x.Id == request.Dob.Value);
    //same applies to top depending on your condition, can be !=, <=, >=
}

//the ONLY part which the query will be executed
var result = query.ToList();

【讨论】:

  • 这不是我所期望的......在这里您正在获取数据并在不同的条件下运行......这会导致性能问题。我需要根据其输入形成条件查询并将其传递给上下文以获取数据
  • @user12073927 它尚未运行,尚未获取,因为我将查询设置为 AsQueryable,它只会在执行 ToListFirstOrDefault 并构建 .Where 条件时执行
  • @user12073927 尝试使用SQL profiler 看看它在使用条件调用query.ToList() 之前不会执行
  • @user12073927 在这里解释stackoverflow.com/a/32827707/2122217
  • 会添加多个条件吗?我已经尝试过使用谓词过滤器,它现在正在工作..谢谢?
猜你喜欢
  • 2014-12-19
  • 1970-01-01
  • 1970-01-01
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2015-11-15
  • 1970-01-01
相关资源
最近更新 更多