1

假设我有一个包含列的产品表:Id、Name、Price 并使用 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 的新列(假设它也是双列)将添加到 Products 表中,有什么方法可以自动知道吗?

对于自动说我的意思是添加代码来做到这一点或得到一个例外?(我假设我无法控制表的列,也无法提前了解表架构的任何更改)

4

2 回答 2

3

你没记错,毛里西奥。以下代码显示了如何创建或更新架构。当 Validate() 引发异常时,更新将运行。当某个字段在数据库中可用但在配置中不可用时,不会抛出异常。拥有额外的字段是完全合法的:你不希望它们被删除,我希望?这可能会造成巨大的伤害...

下面的代码显示了测试、创建、验证和更新,每个步骤都有正确的异常处理。代码已简化,但它应该让您了解如何进行验证。

此代码有助于以实体为中心 (POCO) ORM 配置,您可以在其中向您的类添加一个字段,它将在数据库中自动更新。不是以表格为中心,字段领先。

// executes schema script against database
private static void CreateOrUpdateSchema(Configuration config)
{
    // replace this with your test for existence of schema
    // (i.e., with SQLite, you can just test for the DB file)
    if (!File.Exists(DB_FILE_NAME))
    {
        try
        {
            SchemaExport export = new SchemaExport(config);
            export.Create(false, true);
        }
        catch (HibernateException e)
        {
            // create was not successful
            // you problably want to break out your application here
            MessageBox.Show(
                String.Format("Problem while creating database: {0}", e),
                "Problem");
        }
    }
    else
    {

        // already something: validate
        SchemaValidator validator = new SchemaValidator(config);
        try
        {
            validator.Validate();
        }
        catch (HibernateException)
        {
            // not valid, try to update
            try
            {
                SchemaUpdate update = new SchemaUpdate(config);
                update.Execute(false, true);
            }
            catch (HibernateException e)
            {
                // update was not successful
                // you problably want to break out your application here
                MessageBox.Show(
                    String.Format("Problem while updating database: {0}", e),
                    "Problem");
            }
        }
    }
}

-- 亚伯 --

于 2009-09-09T20:15:24.403 回答
0

您可以使用NHibernate 的 SchemaValidator,但 IIRC 它只检查您的映射实体是否有效,因此它不会检查是否有比映射属性更多的列,因为这不会真正破坏您的应用程序。

于 2009-08-28T23:33:45.640 回答