如何编写Nhibernate查询

时间:2014-01-06 04:40:01

标签: c# sql linq asp.net-mvc-4 nhibernate

我有两个类在数据库中映射。这些表之间具有主键和外键关系,字段为“DeptId”。

Employee.cs

 public class Employee: Entity
    {
        public virtual Int32 Id { get; set; }
        public virtual string Name { get; set; }
        public virtual string Gender { get; set; }
        public virtual Int32 Age { get; set; }
        public virtual string Designation { get; set; }
        public virtual bool Enabled { get; set; }
        public virtual int CreatedById { get; set; }
        public virtual DateTime CreatedDate { get; set; }
        public virtual int? LastModifiedById { get; set; }
        public virtual DateTime? LastModifiedDate { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Department Department { get; set; }
    }

Department.cs

public class Department
    {
        public virtual int DeptId { get; set; }
        public virtual string DeptName { get; set; }
        public virtual bool Enabled { get; set; }
    }

由于我是NHibernate的新手,我无法使用QueryOver编写更复杂的Linq查询。我写了以下查询但是如何编写更多高级查询。请为我提供样本查询和参考资料。

var query = Session.QueryOver<Employee>().List(); 

4 个答案:

答案 0 :(得分:12)

NHibernate查询的文档非常好并且完整。您可以在这里找到基本知识:

此处记录了QueryOver API,它是Criteria的完整类型版本:

开始观察API文档。很快你会发现它是非常逻辑的(.Where()构建WHERE,.Select()来调整SELECT ....)。之后,如果有任何问题,那么SO就是如何

从16.1调整为员工的例子:

var list = session
        .QueryOver<Employee>()
        .WhereRestrictionOn(c => c.Age).IsBetween(18).And(60)
        .Select(c => c.Name)
        .OrderBy(c => c.Name).Asc
        .List<string>();

加入部门(16.4调整后的例子)

var query = session
        .QueryOver<Employee>()
        .JoinQueryOver(e => e.Department)
            .Where(k => k.DeptName == "Director");

答案 1 :(得分:1)

查询的结构

使用以下语法从ISession创建查询:

IList<Department> Dept=
session.QueryOver<Department>()
    .Where(c => c.DeptName == "Max")
    .List();

答案 2 :(得分:1)

简单的LINQ查询被视为NHibernate查询,但您必须将它们连接到存储库。

将实体与Repository和IRepository连接以降低其复杂性。

它会更有条理。

使用此链接了解实体和存储库之间的连接。 http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

如果我把你带到了正确的轨道,请告诉我。

答案 3 :(得分:0)

这是完整的样本

using DB.Extensions;
using DB.Modellers;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Helpers;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NHibernate.Tool.hbm2ddl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace DB
{
    public class DatabaseAdapter
    {
        public List<IConvention> DatabaseConventions { get; set; }
        ISessionFactory sessionFactory;
        public string SqlFilePath { get; }
        public DatabaseAdapter(string sqlFilePath)
        {
            this.SqlFilePath = sqlFilePath;
            if (sessionFactory == null)
                sessionFactory = InitializeSessionFactory();
        }
       
        public ISession GetSession()
        {
            // For now, this will create a new session - However, eventually we could re-use sessions within threads, HTTP request context, etc
            return sessionFactory.OpenSession();
        }

        public IStatelessSession GetStatelessSession()
        {
            return sessionFactory.OpenStatelessSession();
        }
        ISessionFactory InitializeSessionFactory()
        {
             //var conventions = new IConvention[]
             //{
             //    Table.Is(x => x.EntityType.Name.ToLowerInvariant()), // All table names are lower case
             //    ForeignKey.EndsWith("Id"), // Foreign key references end with Id
             //    DefaultLazy.Always() // Enable Lazy-Loading by default
             //}.Concat(DatabaseConventions.NeverNull()).ToArray();

             var config = Fluently.Configure()
               .Database(GetMonoSQLConfiguration())
               .Mappings(m =>
               {
                   m.FluentMappings.Conventions.Setup(c => c.Add(AutoImport.Never()));
                   m.FluentMappings.Conventions.AddAssembly(Assembly.GetExecutingAssembly());
                   m.HbmMappings.AddFromAssembly(Assembly.GetExecutingAssembly());

                   var assembly = Assembly.Load("DB");
                   m.FluentMappings.Conventions.AddAssembly(assembly);
                   m.FluentMappings.AddFromAssembly(assembly);
                   m.HbmMappings.AddFromAssembly(assembly);
               });
            var nhConfig = config.BuildConfiguration();
            var session = config.BuildSessionFactory();
            return session;
        }
        
        private IPersistenceConfigurer GetMonoSQLConfiguration()
        {
            var sql = SQLiteConfiguration.Standard.UsingFile(this.SqlFilePath)
             .ShowSql();
            return sql;
        }
        public void Dispose()
        {
            if (sessionFactory != null)
                sessionFactory.Dispose();
        }

        public void SaveUpdate()
        {
            using (var session = GetSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var existingItem = session.QueryOver<books>()
                       .Where(p => p.number == 1)
                       .Where(p => p.human == "U")
                       .SingleOrDefault();

                    if (existingItem != null) // Update existing
                    {
                        existingItem.number = 1;
                        session.Update(existingItem);
                    }
                    else // Create 
                    {
                        session.Save(new books());
                    }
                    transaction.Commit();
                }
            }
        }
        public IEnumerable<books> GetBooks()
        {
            using (var session = GetStatelessSession())
            {
                var books = session.QueryOver<books>().List();
                return books;
            }
        }
        public IEnumerable<chapters> GetChapters(books books)
        {
            using (var session = GetStatelessSession())
            {
                var items = session.QueryOver<chapters>().Where(p=>p.reference_human == books.human).List();
                return items;
            }
        }
        public IEnumerable<verses> GetVerses()
        {
            using (var session = GetStatelessSession())
            {
                var items = session.QueryOver<verses>().List();
                return items;
            }
        }
    }
}