我有一个用于携带过滤数据的类。我想根据过滤选项从数据库中检索数据。 我的 FilteringDto 类:
public class FilteringDto
{
public int id { get; set; }
public string search_text { get; set; }
}
我想从 CafeTableGroup
表中检索数据。这是我的查询的样子:
using (ISession session = SessionFactory.OpenSession)
{
using (ITransaction transaction = session.BeginTransaction())
{
groups = session.CreateCriteria<CafeTableGroup>().List<CafeTableGroup>();
if (string.IsNullOrEmpty(filters.search_text))
{
groups = groups.Where(a => a.field_1.Like(filters.search_text)).ToList();
}
if (filters.id != 0)
{
groups = groups.Where(a => a.field_2== filters.id).ToList();
}
transaction.Commit();
}
}
但是我这里有个问题。为了获得过滤后的数据,首先它会检索表中的所有数据,然后根据条件进行过滤。有什么方法可以使用单个查询来完成,并且只检索过滤后的数据而不是所有数据?提前致谢。
最佳答案
您的代码中的问题是 .List<CafeTableGroup>();
这导致实例化过早。只需延迟调用 List
.
我没有使用您的确切示例。另外,我的代码使用 IQueryOver
而不是 CreateCriteria
.您可以使用如下代码实现此目的:
public IList<Table1Entity> GetList(FilterParams filterParams = null, PageParams pageParams = null)
{
IList<Table1Entity> instance = null;
Conjunction conjTable1 = Restrictions.Conjunction();
Conjunction conjTable2 = Restrictions.Conjunction();
if(filterParams == null)
filterParams = new FilterParams();
if(!string.IsNullOrEmpty(filterParams.Date))
conjTable1.Add(Restrictions.Eq(Projections.Property<Table1Entity>(x => x.Date), filterParams.Date));
if(!string.IsNullOrEmpty(filterParams.FromTime))
conjTable1.Add(Restrictions.Eq(Projections.Property<Table1Entity>(x => x.FromTime), filterParams.FromTime));
if(!string.IsNullOrEmpty(filterParams.ToTime))
conjTable1.Add(Restrictions.Eq(Projections.Property<Table1Entity>(x => x.ToTime), filterParams.ToTime));
if(!string.IsNullOrEmpty(filterParams.Id))
conjTable1.Add(Restrictions.Eq(Projections.Property<Table1Entity>(x => x.Id), Guid.Parse(filterParams.Id)));
if(!string.IsNullOrEmpty(filterParams.Pid))
conjTable2.Add(Restrictions.Eq(Projections.Property<Table2Entity>(x => x.Pid), Guid.Parse(filterParams.Pid)));
IQueryOver<Table1Entity> query = NHSession.QueryOver<Table1Entity>()
.Where(conjTable1)
.JoinQueryOver(x => x.Table2)
.And(conjTable2);
if(pageParams != null)
query = query.Skip(pageParams.SkipRecords).Take(pageParams.TakeRecords);
instance = query.List();
return instance;
}
这也演示了如何实现连接和分页。
关于c# - 使用 SQL 查询中的条件查询串联从数据库中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47172682/