【问题标题】:Generate a dynamic query accepting any Entity生成接受任何实体的动态查询
【发布时间】:2019-02-07 12:32:32
【问题描述】:

我正在尝试使用 LINQ 创建查询,然后我想将生成的查询分配给实体类。 例如,我有三个具有相同列的实体。

  • 一个 |姓名、姓氏
  • B |姓名、姓氏
  • C |姓名、姓氏

例如,我可以生成一个 Linq Where Closures,首先执行一个包含实体选择的 var。

var lQuery = A.Select(t => t);

如果 Name 或 LastName 不为 null,则添加闭包

if (!string.IsNullOrEmpty(pName))
{
    lQuery = lQuery.Where(x => x.Name == pName);                    
}
if (!string.IsNullOrEmpty(pLastName))
{
    lQuery = lQuery.Where(x => x.LastName == pLastName);
}

最后我从生成的 lQuery 中返回一个 A 列表。

有没有办法生成查询,然后在最后将其分配给我的一个实体?

【问题讨论】:

  • 请发布一些代码 sn-ps 以便我们看到您要执行的操作
  • 我不确定,但我认为您正在寻找 IQueryable,请查看:codeproject.com/Articles/1240553/…
  • Is there a way to generate a query and then assign it at the end to one of my entities?-我不清楚。您是否期望对所有三个实体进行通用查询和过滤?
  • 是的,没错。但我不知道使用 IQueryable 是否有效,我正在尝试将 IQueryable 与另一个包含实体表中相同列的类一起使用。
  • @JohanSánchez 请检查我更新的答案。我已经在我身边检查了它并且它有效。

标签: c# entity-framework linq


【解决方案1】:

你可以这样做:

public async Task<List<object>> GetFilteredEntityList(string entityClassName, string name, string lastName)
{
      var type = Assembly.GetExecutingAssembly()
                .GetTypes()
                .FirstOrDefault(t => t.Name == entityClassName);

      if (type != null)
      {
         DbSet dbSet = _dbContext.Set(type);

         IQueryable entityListQueryable = dbSet;
         if (!string.IsNullOrEmpty(name))
         {
              entityListQueryable = entityListQueryable.Where("Name == @0", name);
         }

         if (!string.IsNullOrEmpty(lastName))
         {
              entityListQueryable = entityListQueryable.Where("LastName == @0", lastName);
         }

         return await entityListQueryable.ToListAsync();
     }
     else
     {
        throw new Exception("Table name does not exist with the provided entity class name");
     }
}

而上述方法的通用版本是:

public class FilterEntity<TEntity> where TEntity: class
{
    YourDbContext _dbContext = new YourDbContext();
    public async Task<List<TEntity>> GetFilteredEntityList(string name, string lastName)
    {
        DbSet<TEntity> dbSet = _dbContext.Set<TEntity>();

        IQueryable<TEntity> entityListQueryable = dbSet;
        if (!string.IsNullOrEmpty(name))
        {
            entityListQueryable = entityListQueryable.Where("Name == @0", name);
        }

        if (!string.IsNullOrEmpty(lastName))
        {
            entityListQueryable = entityListQueryable.Where("LastName == @0", lastName);
        }

        return await entityListQueryable.ToListAsync();
    }
}

及用法:

List<Teacher> teachreList = await new FilterEntity<Teacher>().GetFilteredEntityList("Tanvir", null);

注意:别忘了从Nuget安装System.Linq.Dynamic

【讨论】:

  • 在这段代码中,你使用的是 System.Linq;??,我不能使用 entityListQueryableWhere 闭包/b>
  • 请查看我更新的答案。我错过了告诉你安装System.Linq.Dynamic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-02
  • 2021-10-31
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2021-09-06
相关资源
最近更新 更多