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

时间:2018-01-23 12:09:41

标签: ormlite-servicestack

我喜欢通过在数据库层中定义任何属性来保持我的数据模型干净(并且不依赖于任何Servicestack DLL)。但是,由于升级到ver 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表。 DataItem2的表无法使用代码中定义的任何attibubes。

1 个答案:

答案 0 :(得分:2)

问题是JsConfig.InitStatics()的静态构造函数需要在Startup上初始化一次,这会重新初始化ServiceStack Serializers中的静态配置(以及添加的动态属性)。

这在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"));
//...
相关问题