您可以执行以下操作:
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);
注意:不要忘记安装
System.Linq.Dynamic
从
Nuget