无法使用NHibernate检索数据

时间:2014-07-30 18:55:21

标签: c# nhibernate

我目前正在研究NHibernate,我遇到了第一个应用程序的问题

我的模特:

public class Customer
{
    public virtual int Id { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
}

映射:

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" 
                   assembly="ConsoleApplication1" 
                   namespace="ConsoleApplication1">

  <class name="Customer">
    <id name="Id">
      <generator class="native" />
    </id>
    <property name="FirstName" />
    <property name="LastName" />
  </class>

</hibernate-mapping>

NHibernate配置和检索数据

static void Main(string[] args)
        {
            var connectionConfiguration = new Configuration();
            connectionConfiguration.DataBaseIntegration(x =>
            {

            x.ConnectionString = "Server=localhost;Database=NHibernateTutorial;Trusted_Connection=True;";
            //Defining SQL Server as our DB
            x.Driver<SqlClientDriver>();
            //Defining the SQL Server version as 2012
            x.Dialect<MsSql2012Dialect>();
        });

        //Defifnig the local assembly as the assembly were the mapping file can be found
        connectionConfiguration.AddAssembly(Assembly.GetExecutingAssembly());

        //Start a connection to the DB
        var sessionFactory = connectionConfiguration.BuildSessionFactory();
        using (var session = sessionFactory.OpenSession())
        {
            //Begin a transaction
            using (var transaction = session.BeginTransaction())
            {
                var customers = session.CreateCriteria<Customer>().List<Customer>();
                foreach (var customer in customers)
                {
                    Console.WriteLine(customer.FirstName);
                }
                //Flush the data and end the transaction 
                transaction.Commit();
            }
        }
    }

没有抛出异常并且已经建立了与DB的连接。但是,我无法从Customer表中检索任何数据(客户为空)。我猜测问题与映射有关,但我无法确定...有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你几乎就在那里,你的所有设置都是正确的,只有一个丢失了。您的映射文件必须可用于NHibernate,这意味着:

  • 映射文件必须命名为xxx.hbm.xml,例如 Customer.hbm.xml (可以更改的默认约定,但是......使用.hbm.xml
  • 映射文件 (每个) 必须标记为嵌入式资源。因此,在解决方案资源管理器中选择该文件,单击属性(ala F4)并设置 Build Action: Embedded Resource

现在您的代码将开始提供数据。