NHibernate schemupdate仍然需要重新创建表

本文关键字:创建 新创建 schemupdate NHibernate | 更新日期: 2023-09-27 18:10:57

我在SQL Server 2012上使用NHibernate,我决定使用SchemaUpdater而不是SchemaExport,因为我不想让我的数据消失。我创建了这样的方法:

 public void UpdateSchema(Configuration config)
    {
        System.Action<string> updateExport = x =>
        {
            using (var file = new System.IO.FileStream(@"C:'tmp'update.sql", System.IO.FileMode.Append, System.IO.FileAccess.Write))
            using (var sw = new System.IO.StreamWriter(file))
            {
                sw.Write(x);
                sw.Close();
            }
        };
        NHibernate.Tool.hbm2ddl.SchemaUpdate SchemaUpdater = new NHibernate.Tool.hbm2ddl.SchemaUpdate(config);
        SchemaUpdater.Execute(updateExport, true); 
    }

我的数据库正在创建,但当我想添加新的字段到我的模型,我得到一个错误:"Invalid column name 'xxx'. ↵Invalid column name 'xxx'."

我决定调试和检查SchemaUpdater。例外情况有:

Count = 4
[0]: {"There is already an object named 'User' in the database."}
[1]: {"There is already an object named 'FK5E008E27F9F9FA61' in the database.'r'nCould not create constraint. See previous errors."}
[2]: {"There is already an object named 'FK5E008E27194964AD' in the database.'r'nCould not create constraint. See previous errors."}
[3]: {"There is already an object named 'FK5E008E27713F97F9' in the database.'r'nCould not create constraint. See previous errors."}

这看起来像是程序仍然想要创建新表,而不是更新它,sql创建并发送给db:

create table [User] (
    Id INT IDENTITY NOT NULL,
   Acount NVARCHAR(255) null,
   Email NVARCHAR(255) null,
   (...)
   xxx NVARCHAR(255) null,
   Manager_id INT null,
   Evaluator_id INT null,
   WorkTimeAdmin_Id INT null,
   primary key (Id)
)
alter table [User] 
    add constraint FK5E008E27F9F9FA61 
    foreign key (Manager_id) 
    references [User]
alter table [User] 
    add constraint FK5E008E27194964AD 
    foreign key (Evaluator_id) 
    references [User]
alter table [User] 
    add constraint FK5E008E27713F97F9 
    foreign key (WorkTimeAdmin_Id) 
    references [User]

我真的想要一个自动化的解决方案,所以没有复制和编辑sql的有什么要改的吗?

NHibernate schemupdate仍然需要重新创建表

您永远不需要显式地运行schemupdate。Configuration实例可以接受属性"hbm2ddl"。auto" (NHibernate.Cfg.Environment.Hbm2ddlAuto),当设置为"update" (SchemaAutoAction.Update)时,将在需要时更新数据库。

除了Ricardo的回答之外,这里还有一个hbm2ddl。设置Auto属性。"update"指示会话工厂创建不存在的表,如果模式和相对模型不同,则更新现有的表。我知道"update"是区分大小写的,所以"update"不起作用。

.ExposeConfiguration(cfg => {
                    cfg.SetProperty("hbm2ddl.auto", "update"); // Updates or creates tables                                                
                })