Dio Phung
Dio Phung

Reputation: 6282

How to verify if NHibernate hbm.xml are matching with a particular SQL schema?

I had an ASP.NET MVC web application, using NHibernate as ORM on SQL Server 2008 R2. When we deployed to the server, we can update our database any time (some are ad-hoc changes).

The problem is when the database schema change, the application crashed because NHibernate .hbm.xml files are no longer matching with the DB schema.

How do I verify that my current *.hbm.xml file are matching with the database schema ? And how to detect the mismatch early in ASP.NET MVC ?

Upvotes: 0

Views: 401

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You can do the checking when application runs, could be in the global asax.

protected void Application_Start()
{
}

The connection string is the key to get the expected schema.

<property name="connection.connection_string">Server=.;Initial Catalog=TheExpectedSchema; ..</property>

First read the expected schema by reading it from nhibernate config and retrieve it from Initial Catalog part (if the database is oracle, probably use the User ID part).

NHibernate.Cfg.Configuration config = ...;

var conStr = config.Properties["connection.connection_string"];
var match = Regex.Match(conStr, "Initial Catalog *= *([^;]*) *");
var expectedSchema = match.Groups[1].Value;

Then read the actual schema by reading it from *.hbm.xml file.

<hibernate-mapping schema="TheActualSchema" 

If the files are put under App_Data directory, read each file and use xml document to get the schema.

var appDataDir = new DirectoryInfo(HttpContext.Server.MapPath("~/App_Data"));
var files = appDataDir.GetFiles("*.hbm.xml");
foreach (var file in files)
{
    var doc = new XmlDocument();
    doc.Load(file.FullName);

    var actualSchema = doc.DocumentElement.GetAttribute("schema");
    if (actualSchema != expectedSchema)
    {
        // Proper handling here (an example would be throwing exception).
        throw new Exception(string.Format("Expected schema: {0}, actual schema {1}", expectedSchema, actualSchema));
    }
}

Upvotes: 1

Related Questions