Is there a way to use SessionFactory.GetClassMetadata()
, or any other method you're aware of, to dynamically get the maximum size of a varchar
column that underlies an NHibernate class' string property?
To clarify, I'm not looking to read a length attribute that's specified in the NHibernate mapping file. I want to deduce the actual database column length.
See the code below for two different ways you can get the column size for a string from NHib metadata.
Cheers,
Berryl
[Test]
public void StringLength_DefaultIs_50_v1()
{
_metadata = _SessionFactory.GetClassMetadata(typeof(User));
var propertyType = _metadata.GetPropertyType("Email") as StringType;
Assert.That(propertyType.SqlType.Length, Is.EqualTo(50));
}
[Test]
public void StringLength_DefaultIs_50_v2()
{
var mapping = _Cfg.GetClassMapping(typeof(User));
var col = mapping.Table.GetColumn(new Column("Email"));
Assert.That(col.Length, Is.EqualTo(50));
}
When the Session factory is generated the NH engine does not check (and retrieve) what the underlying database is. For your case either you provide a "rich" mapping to have everything available at runtime, OR make a function that reads the necessary information from the DB (ie select * from sys.columns ..... for sql-server) when you need it.
Mind you that a rich mapping also allows the NH engine to make some automations (like checking if the size of the string passed is larger than the length of the (n)varchar column)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With