我正在尝试使用LINQ创建查询,然后将生成的查询分配给实体类。 例如,我有三个具有相同列的实体。
例如,我可以生成一个Linq,其中Closures首先执行包含实体选择的变量。
var lQuery = A.Select(t => t);
然后如果Name或LastName不为空,则添加闭包
if (!string.IsNullOrEmpty(pName))
{
lQuery = lQuery.Where(x => x.Name == pName);
}
if (!string.IsNullOrEmpty(pLastName))
{
lQuery = lQuery.Where(x => x.LastName == pLastName);
}
最后,我从生成的lQuery中返回A的列表。
是否可以生成查询,然后在最后将其分配给我的一个实体?
答案 0 :(得分:0)
您可以执行以下操作:
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");
}
}
上述方法的 Generic 版本是:
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