Ormlite: Setting model attributes in c# no longer works

I like to keep my data models clean (and not dependent on any Servicestack DLLs) by defining any attributes just in the database layer. However since upgrading to ver 5.0, my application fails to correctly recognise attributes set in c# using AddAttributes().

The code below shows a minimal reproducable example.

using ServiceStack;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;

namespace OrmliteAttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var type = typeof(DataItem2);
            type.AddAttributes(new AliasAttribute("DataItem2Table"));
            var prop = type.GetProperty(nameof(DataItem2.ItemKey));
            if (prop != null)
                prop.AddAttributes(new PrimaryKeyAttribute());
            prop = type.GetProperty(nameof(DataItem2.ItemDescription));
            if (prop != null)
                prop.AddAttributes(new StringLengthAttribute(100));

            SqlServerDialect.Provider.GetStringConverter().UseUnicode = true;

            var connectionString = @"Data Source=localhost\sqlexpress; Initial Catalog=OrmLiteTest; Integrated Security=True;";
            var connectionFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);

            using (var db = connectionFactory.OpenDbConnection())
            {
                db.CreateTableIfNotExists<DataItem>();
                db.CreateTableIfNotExists<DataItem2>();
            }
        }
    }

    [Alias("DataItemTable")]
    public class DataItem
    {
        [PrimaryKey]
        public int ItemKey { get; set; }

        [StringLength(100)]
        public string ItemDescription { get; set; }
    }

    public class DataItem2
    {
        public int ItemKey { get; set; }
        public string ItemDescription { get; set; }
    }
}

The table for DataItem is created correctly using the attributes as specified. The table for DataItem2 fails to use any of the attibubes defined in the code.

Since this was also asked on StackOverflow I’ve answered it there as it’s more discoverable.

Essentially the solution is to initialize the OrmLiteConnectionFactory before adding attributes:

var connectionFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);

var type = typeof(DataItem2);
type.AddAttributes(new AliasAttribute("DataItem2Table"));
//...

Or explicitly call JsConfig.InitStatics(); instead, e.g:

JsConfig.InitStatics();

var type = typeof(DataItem2);
type.AddAttributes(new AliasAttribute("DataItem2Table"));
//...