做个一个 一对多的NHibernateDemo,数据库中有两张表,一个是Dept(部门表),另一个是Users(员工表),两表之间有主外键关系。老是提示Could not compile the mapping document:XXXX.hbm.xml,请大家帮忙看看!
    下面是SQL数据库脚本
create database OnetoMany
gocreate table Dept
(
 Id          int  identity(1,1)    Primary Key,
 DeptName    nvarchar(50)          Not Null,  --部门名称
 DeptCode    nvarchar(50)    Not Null   --部门代码
)
gocreate table Users
(
 Id  int identity(1,1)  Primary Key,
 DeptId      int    Not Null,  --部门id
 UserName    nvarchar(50)    Not Null,  --员工姓名
 UserCode    nvarchar(50)    Not Null   --员工代码
)
go
实体类OM文件夹下的Entity文件夹里下面是dept.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace OM.Entity
{
    public class dept
    {
         public virtual int Id { get; set; }
         public virtual string DeptName { get; set; }
         public virtual string DeptCode { get; set; }
         public virtual ISet<users> userss { get; set; }
    }
}下面是users.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace OM.Entity
{
    public class users
    {
        public virtual int Id { get; set; }
        public virtual int DeptId { get; set; }
        public virtual string UserName { get; set; }
        public virtual string UserCode { get; set; }
        public virtual dept Depts { get; set; }
    }
}
映射文件users.hbm.xml和dept.hbm.xml在OM文件夹下的Mapping里下面是dept.hbm.xml<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="OM.Entity" assembly="OM.Entity">
  <class name="dept" table="[Dept">
    <id name="Id">
      <column name="Id" sql-type="int" not-null="true"/>
      <generator class="native" />
    </id>
    <property name="DeptName" column="DeptName" type="string" length="50" not-null="true"/>
    <property name="DeptCode" column="DeptCode" type="string" length="50" not-null="true"/>    <!--一个dept对应多个user-->
    <set name="userss" table="Users" generic="true" inverse="true">
      <key column="DeptId" foreign-key="FK_Users_Dept"/>
      <one-to-many class="users"/>
    </set>
  </class>
</hibernate-mapping>下面是users.hbm.xml<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="OM.Entity" assembly="OM.Entity">
  <class name="users" table="Users">
    <id name="Id">
      <column name="Id" sql-type="int" not-null="true"/>
      <generator class="native" />
    </id>
    <property name="DeptId" column="DeptId" type="int" not-null="true"/>
    <property name="UserName" column="UserName" type="string" length="50" not-null="true"/>
    <property name="UserCode" column="UserCode" type="string" length="50" not-null="true"/>
   
    <!--多对一关系:多个user属于一个dept-->
    <many-to-one name="dept" column="Id" not-null="true" class="dept" foreign-key="FK_Users_Dept"/>
  </class>
</hibernate-mapping>下面是Web.config文件:<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>
  <!-- Add this element -->
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.connection_string">Server=.;initial catalog=OnetoMany;Integrated Security=SSPI</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle</property>
      <mapping assembly="OM.Entity" />
    </session-factory>
  </hibernate-configuration>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
</configuration>下面是NHibernateHelper.cs在App_Code文件夹里using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Cfg;namespace OnetoMany
{
    public class NHibernateHelper
    {
        private const string CurrentSessionKey = "nhibernate.current_session";
        private static readonly ISessionFactory sessionFactory;        static NHibernateHelper()
        {
            sessionFactory = new Configuration().Configure().BuildSessionFactory();
        }        public static ISession GetCurrentSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;            if (currentSession == null)
            {
                currentSession = sessionFactory.OpenSession();
                context.Items[CurrentSessionKey] = currentSession;
            }            return currentSession;
        }        public static void CloseSession()
        {
            HttpContext context = HttpContext.Current;
            ISession currentSession = context.Items[CurrentSessionKey] as ISession;            if (currentSession == null)
            {
                // No current session
                return;
            }            currentSession.Close();
            context.Items.Remove(CurrentSessionKey);
        }        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }    }
}下面是Default.aspx.csusing System.Web.UI.WebControls;
using NHibernate;
using NHibernate.Cfg;
using OM;
using OM.Entity;namespace OnetoMany
{
    public partial class _Default : System.Web.UI.Page
    {
        private ISession session;        public _Default()
        {
            session = NHibernateHelper.GetCurrentSession();
        }        protected void Page_Load(object sender, EventArgs e)
        {
            GetUser();
        }        public void GetUser()  //得到用户信息
        {    
            using (ITransaction tx = session.BeginTransaction())
            {
                IQuery query = session.CreateQuery("select d from dept d inner join d.users u where d.id = :id");
                query.SetString("id", "001");
                foreach (users u in query.Enumerable())
                {
                    lblShow.Text = u.UserCode + u.UserName;
                }
                tx.Commit();
            }            
        }
    }
}

解决方案 »

  1.   

    dept.hbm.xml
     <class name="dept" table="[Dept">
    ??///是不是这里` 是你的配置文件有问题`
      

  2.   

    不是这里问题,现在又提示Could not load file or assembly 'OM.Mapping' or one of its dependencies. 系统找不到指定的文件。Could not load file or assembly 'OM.Mapping' or one of its dependencies. 系统找不到指定的文件。 
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'OM.Mapping' or one of its dependencies. 系统找不到指定的文件。Source Error: 
    Line 15:         static NHibernateHelper()
    Line 16:         {
    Line 17:             sessionFactory = new Configuration().Configure().BuildSessionFactory();
    Line 18:         }
    Line 19: 
     Source File: D:\Lewis\Programs\OnetoMany\OnetoMany\App_Code\NHibernateHelper.cs    Line: 17 Assembly Load Trace: The following information can be helpful to determine why the assembly 'OM.Mapping' could not be loaded.
    === Pre-bind state information ===
    LOG: User = JACK\guopeizhen
    LOG: DisplayName = OM.Mapping
     (Partial)
    WRN: Partial binding information was supplied for an assembly:
    WRN: Assembly Name: OM.Mapping | Domain ID: 13
    WRN: A partial bind occurs when only part of the assembly display name is provided.
    WRN: This might result in the binder loading an incorrect assembly.
    WRN: It is recommended to provide a fully specified textual identity for the assembly,
    WRN: that consists of the simple name, version, culture, and public key token.
    WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
    LOG: Appbase = file:///D:/Lewis/Programs/OnetoMany/OnetoMany/
    LOG: Initial PrivatePath = D:\Lewis\Programs\OnetoMany\OnetoMany\bin
    Calling assembly : NHibernate, Version=2.1.2.4000, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.
    ===
    LOG: This bind starts in default load context.
    LOG: Using application configuration file: D:\Lewis\Programs\OnetoMany\OnetoMany\web.config
    LOG: Using host configuration file: 
    LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v4.0.30128\config\machine.config.
    LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
    LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v4.0.30128/Temporary ASP.NET Files/root/ad302a10/b8aba9bc/OM.Mapping.DLL.
    LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v4.0.30128/Temporary ASP.NET Files/root/ad302a10/b8aba9bc/OM.Mapping/OM.Mapping.DLL.
    LOG: Attempting download of new URL file:///D:/Lewis/Programs/OnetoMany/OnetoMany/bin/OM.Mapping.DLL.
    LOG: Attempting download of new URL file:///D:/Lewis/Programs/OnetoMany/OnetoMany/bin/OM.Mapping/OM.Mapping.DLL.
    LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v4.0.30128/Temporary ASP.NET Files/root/ad302a10/b8aba9bc/OM.Mapping.EXE.
    LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v4.0.30128/Temporary ASP.NET Files/root/ad302a10/b8aba9bc/OM.Mapping/OM.Mapping.EXE.
    LOG: Attempting download of new URL file:///D:/Lewis/Programs/OnetoMany/OnetoMany/bin/OM.Mapping.EXE.
    LOG: Attempting download of new URL file:///D:/Lewis/Programs/OnetoMany/OnetoMany/bin/OM.Mapping/OM.Mapping.EXE. Stack Trace: 
    [FileNotFoundException: Could not load file or assembly 'OM.Mapping' or one of its dependencies. 系统找不到指定的文件。]
       System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
       System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +39
       System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection, Boolean suppressSecurityChecks) +132
       System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +144
       System.Reflection.Assembly.Load(String assemblyString) +28
       NHibernate.Cfg.Configuration.AddAssembly(String assemblyName) +107[MappingException: Could not add assembly OM.Mapping]
       NHibernate.Cfg.Configuration.LogAndThrow(Exception exception) +88
       NHibernate.Cfg.Configuration.AddAssembly(String assemblyName) +182
       NHibernate.Cfg.Configuration.DoConfigure(IHibernateConfiguration hc) +1229
       NHibernate.Cfg.Configuration.Configure() +93
       OnetoMany.NHibernateHelper..cctor() in D:\Lewis\Programs\OnetoMany\OnetoMany\App_Code\NHibernateHelper.cs:17[TypeInitializationException: The type initializer for 'OnetoMany.NHibernateHelper' threw an exception.]
       OnetoMany.NHibernateHelper.GetCurrentSession() in D:\Lewis\Programs\OnetoMany\OnetoMany\App_Code\NHibernateHelper.cs:32
       OnetoMany._Default..ctor() in D:\Lewis\Programs\OnetoMany\OnetoMany\Default.aspx.cs:20
       ASP.default_aspx..ctor() in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30128\Temporary ASP.NET Files\root\ad302a10\b8aba9bc\App_Web_wsivr42a.1.cs:0
       __ASP.FastObjectFactory_app_web_wsivr42a.Create_ASP_default_aspx() in c:\WINDOWS\Microsoft.NET\Framework\v4.0.30128\Temporary ASP.NET Files\root\ad302a10\b8aba9bc\App_Web_wsivr42a.2.cs:0
       System.Web.Compilation.BuildResultCompiledType.CreateInstance() +32
       System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp) +109
       System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +31
       System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath) +40
       System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig) +167
       System.Web.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +128
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184