使用SQL查询中的条件查询连接从数据库中检索数据

时间:2017-11-08 06:08:14

标签: c# nhibernate

我有一个用于携带过滤数据的类。我想根据过滤选项从数据库中检索数据。 我的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();

                    }
                }

但我这里有问题。为了获得过滤数据,首先它检索表中的所有数据,然后根据条件对其进行过滤。有什么方法可以使用单个查询来检索并仅检索过滤后的数据而不是所有数据?提前谢谢。

1 个答案:

答案 0 :(得分:1)

代码中的问题是.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;
}

这也演示了如何实现连接和分页。