开发者

Find Underlying Column Size Via NHibernate Metadata

开发者 https://www.devze.com 2022-12-15 03:25 出处:网络
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 prope

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 lookin开发者_开发百科g 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)

0

精彩评论

暂无评论...
验证码 换一张
取 消