views:

277

answers:

4

Hi,

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.

Thanks,

Calvin

A: 

Anyone?

I'm starting to believe accessing the actual database metadata is not possible.

Calvin Nguyen
A: 

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)

Jaguar
A: 

Thanks, Jaguar. By rich mapping do you just mean a mapping that contains length attributes that correspond to database column sizes?

Calvin Nguyen
yesbtw commenting on my answer would have alerted me on your comment. Answers are not to be used for a discussion
Jaguar
+1  A: 

Hi Calvin

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));
    }
Berryl