Ormlite:在 C# 中设置模型属性不再有效

Ormlite: Setting model attributes in c# no longer works

我喜欢通过只在数据库层定义任何属性来保持我的数据模型干净(并且不依赖于任何 Servicestack DLL)。但是,自从升级到 5.0 版后,我的应用程序无法使用 AddAttributes() 正确识别在 c# 中设置的属性。

下面的代码显示了一个最小的可重现示例。

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

使用指定的属性正确创建了 DataItem 的 table。 DataItem2 的 table 未能使用代码中定义的任何属性。

问题是 JsConfig.InitStatics() 的静态构造函数需要在启动时初始化一次,这会重新初始化 ServiceStack 序列化程序中的静态配置(和添加的动态属性)。

这在像 OrmLiteConnectionFactory 这样的 ServiceStack 库中被隐式调用,因为之前没有被调用过,所以会重新初始化 ServiceStack.Text 静态配置。为避免重置动态属性,您可以在添加属性之前初始化 OrmLiteConnectionFactory

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

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;

或者,如果愿意,您可以在添加任何属性之前显式调用 InitStatics(),例如:

JsConfig.InitStatics();

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