【问题标题】:How to write Nhibernate Queries [closed]如何编写 Nhibernate 查询 [关闭]
【发布时间】:2014-01-23 10:51:04
【问题描述】:

我有两个在数据库中映射的类。这些表通过“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(); 

【问题讨论】:

  • 在大多数情况下,您可以使用 LINQ .. 您尝试过什么?你想做什么?
  • 我想实现连接并使用NHibernate的Average Sum等内置函数。
  • 如果有帮助就太好了;) NHibernate 是一个很棒的工具,请不要放弃! ;)

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


【解决方案1】:

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

QueryOver API 是Criteria 的完全类型化版本,记录在此:

开始观察 API 文档。很快你就会发现这是非常合乎逻辑的(.Where() 构建 WHERE,.Select() 调整 SELECT....)。后来,如果有什么问题,SO 里面全是 HOW TO

从 16.1 调整为 Employee 的示例:

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

到 Department 的 JOIN(从 16.4 调整的示例)

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

【讨论】:

  • 这些章节的链接现在已经失效了。
  • 章节的链接再次起作用
【解决方案2】:

简单的 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】:

    这是完整的示例

    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;
                }
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 1970-01-01
      相关资源
      最近更新 更多