NHibernate - 添加新的 属性 到 class

NHibernate - Add new property to class

当我将新的 属性 添加到 class 时,我对 NHibernate 幕后发生的事情感到有点困惑。

当我将 属性 'Price' 添加到 'Item' class 时,我的应用程序在检索 Item 对象时抛出异常,因为这个新的 属性 不是'不在数据库中:

[SqlException (0x80131904): Invalid column name 'Price'.]

每次我在 class 中声明一个新的 属性 时,我是否应该手动向我的数据库 table 添加一个列?

简短的回答是:是的,你是。

您要求 nHibernate 映射到数据库中的 table 的 class 必须仅具有作为列存在于 table 中的属性。如果你想在 class 中添加一个新的 属性,那么你需要在 table.

中添加一列

另一方面,如果您想要 "Price" 属性 用于未保存在数据库中的项目,那么您将在应用程序中有一个不同的 class,而不是在nHibernate的控制下,它包含一个class"Item"的对象,有自己的"Price"属性。

一般来说,每当创建 ISessionFactory 时,我们都可以使用配置设置来更新我们的数据库架构:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
       <property name="hbm2ddl.auto">Update</property>

勾选Table 3.2. NHibernate Configuration Properties

我们甚至可以在自己的代码中做到:

How to update database table schemas with NHibernate schema generation?

(上面问答的片段)

_cfg = new Configuration();
_cfg.Configure();
_cfg.AddAssembly(Assembly.LoadFrom("DataLayer.dll"));
var update = new SchemaUpdate(_cfg);
update.Execute(true, false);

总结,我们可以设置我们的工厂来更新模式,无论何时创建这样的工厂。它可以在 DEV 中使用,但我会说,仅在 DEV 中...