Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Underlying Column Size Via NHibernate Metadata

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.

like image 591
Calvin Nguyen Avatar asked Dec 23 '09 00:12

Calvin Nguyen


2 Answers

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));
    }
like image 130
Berryl Avatar answered Nov 15 '22 10:11

Berryl


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)

like image 24
Jaguar Avatar answered Nov 15 '22 10:11

Jaguar