使用NHibernate / ActiveRecord进行自动架构验证

时间:2009-08-28 20:18:50

标签: nhibernate castle-activerecord

假设我有一个包含列的产品表: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表中,有什么方法可以自动知道吗?

为了自动说我的意思是添加代码来做到这一点或获得异常? (我假设我无法控制桌子的列或方法 事先了解表格架构的任何变化)

2 个答案:

答案 0 :(得分:3)

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

以下代码显示了测试,创建,验证和更新,每个步骤都有正确的异常处理。代码已经过简化,但它可以帮助您了解如何进行验证。

此代码有助于以实体为中心(POCO)O​​RM配置,您可以在其中向类添加字段,它将自动在数据库中更新。不以表格为中心,字段在哪里。

// 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");
            }
        }
    }
}

- Abel -

答案 1 :(得分:0)

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

相关问题