【问题标题】:Can't retrieve data using NHibernate无法使用 NHibernate 检索数据
【发布时间】:2014-07-30 18:55:21
【问题描述】:

我目前正在学习 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();
            }
        }
    }

未引发异常,并且已建立与数据库的连接。但是我无法从客户表中检索任何数据(客户为空)。我猜问题出在映射上,但我不能确定...有什么建议吗?

【问题讨论】:

  • 如果客户表中有数据,那么这应该有效。如果桌子是空的,那么客户也是空的。我看不到任何插入,所以我不确定是否有数据。你为什么不尝试插入然后选择看看它是否有效?

标签: c# nhibernate


【解决方案1】:

您快到了,您的所有设置都正确,只是缺少一个。您的映射文件必须可用于 NHibernate,这意味着:

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

现在您的代码将开始传递数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多