使用NHibernate/ActiveRecord进行自动模式验证
假设我有一个产品表,列为:Id、Name、Price 我使用NHibernate(或ActiveRecord)将表映射到POCO:使用NHibernate/ActiveRecord进行自动模式验证,nhibernate,castle-activerecord,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; } } 现在,如果有一天出现一个名为ShipmentPric
public class Product
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
public virtual double Price { get; set; }
}
现在,如果有一天出现一个名为ShipmentPrice的新列(假设它也是双倍的)
将被添加到产品表中,是否有任何方法可以自动知道
自动地说,我的意思是添加代码来做这件事,还是得到一个异常?
(我假设我无法控制表中的列,也无法
提前知道表架构的任何更改)您可以使用,但IIRC it只检查映射的实体是否有效,因此不会检查是否有超过映射属性的列,因为这不会真正破坏您的应用程序。您确实记得正确,Mauricio。下面的代码显示了如何创建或更新架构。当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");
}
}
}
}
--亚伯--