使用 NHibernate/ActiveRecord 自动模式验证
假设我有一个产品表,其中包含以下列:ID、名称、价格 并使用NHibernate(或ActiveRecord)将表映射到POCO:
public class Product
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
}
现在,如果有一天有一个名为ShipmentPrice的新列(我们假设它也是双倍的) 将添加到产品表中,有什么方法可以自动知道这一点吗?
自动地说,我的意思是添加代码来执行此操作或获得异常? (我假设我无法控制表的列或无法控制 提前知道表架构的任何更改)
Let's assume I have a table of Products with columns: Id, Name, Price
and using NHibernate (or ActiveRecord) I map the table to the POCO:
public class Product
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
}
Now if someday a new column named ShipmentPrice (let's assume it's double too)
will be added to the Products table, is there any way I can automatically know that?
For saying automatically I mean adding code to do that or getting an exception?
(I assume I don't have control on the columns of the table or a way to
know of any changes to the table's schema in advance)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

你没记错,毛里西奥。以下代码显示了如何创建或更新架构。当 Validate() 引发异常时,更新将运行。当某个字段在数据库中可用但在配置中不可用时,不会引发异常。拥有额外的字段是完全合法的:我希望您不希望它们被删除?这可能会造成巨大的损害...
以下代码显示了测试、创建、验证和更新,每个步骤都有正确的异常处理。代码已简化,但它应该让您了解如何进行验证。
此代码有助于以实体为中心 (POCO) ORM 配置,您可以在其中向类添加字段,并且它将自动在数据库中更新。不是以表为中心,以字段为主导。
——阿贝尔——
You do recall correctly, Mauricio. The following code shows how you can create or update a schema. The update will run when Validate() raises an exception. No exception will be thrown when a field is available in the database but not in the configuration. It is perfectly legal to have extra fields: you don't want them to be deleted, I hope? That could cause tremendous damage...
The following code shows Test, Create, Validate and Update, each step with the proper exception handling. The code is simplified, but it should give you a handle on how to do a validation.
This code helps with Entity-centric (POCO) ORM configurations, where you can add a field to your class and it will automatically be updated in the database. Not with table-centric, where fields are leading.
-- Abel --