使用 queryover 加入 2 个表

Posted

技术标签:

【中文标题】使用 queryover 加入 2 个表【英文标题】:joining 2 table with queryover 【发布时间】:2011-12-07 17:12:54 【问题描述】:

我在样本中有 3 张桌子。我要加入 2 张桌子,但我有问题 以下是我的代码:

<?xml version="1.0"?>

</configSections>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Server=(local);database=human;Integrated Security=SSPI;</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

using System.Collections.Generic; 
using System.Text; 
using System; 


namespace human 

public class TblStudent 
    public TblStudent()  
    public virtual int ID  get; set; 
    public virtual IList<TblTerm> TblTerms  get; set; 
    public virtual string name  get; set; 
    public virtual string lastname  get; set; 




using System; 
using System.Collections.Generic; 
using System.Text; 
using FluentNHibernate.Mapping;

namespace human 


public class TblStudentMap : ClassMap<TblStudent> 

    public TblStudentMap() 
        Table("TblStudent");
        LazyLoad();
        Id(x => x.ID).GeneratedBy.Identity().Column("ID");
        Map(x => x.name).Column("name");
        Map(x => x.lastname).Column("lastname");
        HasMany(x => x.TblTerms);
    



using System.Collections.Generic; 
using System.Text; 
using System; 


namespace human 

public class TblTerm 
    public TblTerm()  
    public virtual int ID  get; set; 
    public virtual TblLesson TblLesson  get; set; 
    public virtual TblStudent TblStudent  get; set; 



using System; 
using System.Collections.Generic; 
using System.Text; 
using FluentNHibernate.Mapping;

namespace human 


public class TblTermMap : ClassMap<TblTerm> 

    public TblTermMap() 
        Table("TblTerm");
        LazyLoad();
        Id(x => x.ID).GeneratedBy.Identity().Column("ID");
        References(x => x.TblLesson).Column("LessonID");
        References(x => x.TblStudent).Column("StudentID");
    



using System; 
using System.Collections.Generic; 
using System.Text; 
using FluentNHibernate.Mapping;

namespace human 


public class TblTermMap : ClassMap<TblTerm> 

    public TblTermMap() 
        Table("TblTerm");
        LazyLoad();
        Id(x => x.ID).GeneratedBy.Identity().Column("ID");
        References(x => x.TblLesson).Column("LessonID");
        References(x => x.TblStudent).Column("StudentID");
    



 private void button_JoinSelect_Click(object sender, EventArgs e)
    
        var cfg = new Configuration();
        PersistenceModel pm = new PersistenceModel();
        pm.AddMappingsFromAssembly(typeof(human.TblStudent).Assembly);
        pm.Configure(cfg);
        ISessionFactory factory = cfg.BuildSessionFactory();

        using (var session = factory.OpenSession())
        
            using (var trans = session.BeginTransaction())
            
                var query = session.QueryOver<TblStudent().JoinQueryOver<TblTerm>
      (c=> c.TblTerms).List();
                trans.Commit();
                dataGridView1.DataSource = query;
            
        
      

我的错误:

NHibernate.Exceptions.GenericADOException:无法执行查询 [ SELECT this_.ID as ID1_1_, this_.name as name1_1_, this_.lastname as lastname1_1_, tblterm1_.ID as ID2_0_, tblterm1_.LessonID as LessonID2_0_, tblterm1_.StudentID as StudentID2_0_ FROM TblStudent this_inner join TblTerm tblterm1_ on this_.ID=tblterm1_ .TblStudent_id ] [SQL: SELECT this_.ID as ID1_1_, this_.name as name1_1_, this_.lastname as lastname1_1_, tblterm1_.ID as ID2_0_, tblterm1_.LessonID as LessonID2_0_, tblterm1_.StudentID as StudentID2_0_ FROM TblStudent this_inner join TblTerm tblterm1_ on this_.ID =tblterm1_.TblStudent_id] ---> System.Data.SqlClient.SqlException:列名“TblStudent_id”无效。 在 System.Data.SqlClient.SqlConnection.OnError(SqlException 异常,布尔 breakConnection) 在 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException 异常,布尔 breakConnection) 在 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() 在 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior,SqlCommand cmdHandler,SqlDataReader dataStream,BulkCopySimpleResultSet bulkCopyHandler,TdsParserStateObject stateObj) 在 System.Data.SqlClient.SqlDataReader.ConsumeMetaData() 在 System.Data.SqlClient.SqlDataReader.get_MetaData() 在 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,RunBehavior runBehavior,字符串 resetOptionsString) 在 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔返回流,布尔异步) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,String 方法,DbAsyncResult 结果) 在 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布尔 returnStream,String 方法) 在 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior 行为,字符串方法) 在 System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior 行为) 在 System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader() 在 NHibernate.AdoNet.AbstractBatcher.ExecuteReader(IDbCommand cmd) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\AdoNet\AbstractBatcher.cs:line 247 在 NHibernate.Loader.Loader.GetResultSet(IDbCommand st, Boolean autoDiscoverTypes, Boolean callable, RowSelection selection, ISessionImplementor session) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1349 在 NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 413 在 NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 243 在 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1694 --- 内部异常堆栈跟踪结束 --- 在 NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1703 在 NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1601 在 NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet1 querySpaces, IType[] resultTypes) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1595 at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Criteria\CriteriaLoader.cs:line 74 at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 1919 at NHibernate.Impl.CriteriaImpl.List(IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 265 at NHibernate.Impl.CriteriaImpl.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 276 at NHibernate.Impl.CriteriaImpl.Subcriteria.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 813 at NHibernate.Criterion.QueryOver1.List() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Criterion\QueryOver.cs:line 57 在 NHibernate.Criterion.QueryOver`1.NHibernate.IQueryOver.List() 在 d:\CSharp\NH\NH\nhibernate\src\NHibernate\Criterion\QueryOver.cs:line 198 在 E:\desktop\Human\human\human\Form1.cs:line 84 中的 human.Form1.button_JoinSelect_Click(Object sender, EventArgs e) 处

请指教

【问题讨论】:

什么是完整的异常文本? 无法执行查询 [SELECT this_.ID as ID1_1_, this_.name as name1_1_, this_.lastname as lastname1_1_, tblterm1_.ID as ID2_0_, tblterm1_.LessonID as LessonID2_0_, tblterm1_.StudentID as StudentID2_0_ FROM TblStudent this_inner join TblTerm tblterm1_ on this_.ID=tblterm1_.TblStudent_id ] [SQL: SELECT this_.ID as ID1_1_, this_.name as name1_1_, this_.lastname as lastname1_1_, tblterm1_.ID as ID2_0_, tblterm1_.LessonID as LessonID2_0_, tblterm1_ .StudentID as StudentID2_0_ FROM TblStudent this_inner join TblTerm tblterm1_ on this_.ID=tblterm1_.TblStudent_id] 脑力增强意味着exception.ToString()不是exception.Message 【参考方案1】:

该异常可能是由多种原因造成的。例如,当我试图在我的数据库上运行你的代码而根本没有你的表时,我遇到了同样的错误。尝试检查您的任何表中的任何一条记录是否返回良好,然后尝试使您的加入工作。我没有看到错误,当我正确配置 nh 时,没有抛出异常。试试这个代码而不是你的工厂初始化(在新的新数据库上),它会根据你的映射创建表来查看你的真实表是否相同。

ISessionFactory factory = Fluently.Configure()
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TblStudent>())
            .ExposeConfiguration(config => new SchemaExport(config).Create(false, true));

【讨论】:

以上是关于使用 queryover 加入 2 个表的主要内容,如果未能解决你的问题,请参考以下文章

NHibernate QueryOver 两次加入一个集合

如何使用转换后的 UUID 字段加入 2 个表?

如何将2个表同名行加入一列

NHibernate 使用带有 WHERE IN 的 QueryOver

如何在2个表之间加入新表?

NHibernate 3.0:没有使用QueryOver的FirstOrDefault()?