0

我在 .Net Core 中有两个课程

班上Owner

namespace CustomStoreDatabase.Models
{
    public class Owner
    {
        public string OwnerId { get; set; }
        public DateTime MinDateTime { get; set; }
        public DateTime MaxDateTime { get; set; }
        public TimeSpan Interval { get; set; }//store like a double
        public Ownership Ownership { get; set; } //store like a JSON String in the db
    }
}

和班级Ownership

namespace CustomStoreDatabase.Models
{
    public class Ownership
    {
        public string OwnershipId { get; set; }
        public List<string> TextOutput { get; set; }
        public DateTime DateTime { get; set; }
        public TimeSpan MeanInterval { get; set; }//Store like long ticks, TimeSpan.FromTicks(Int64), TimeSpan.Ticks
    }
}

现在,我想像 String 一样存储 Ownership 类,而 MeanInterval 像 long 一样存储在数据库中。我正在检查thisthis,但我不明白如何应用它。

protected virtual void OnModelCreating (System.Data.Entity.DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Owner>().Property(x => x.Ownership).HasColumnType("text");
    modelBuilder.Entity<Owner>().Property(x => x.Interval).HasColumnType("float");//store like a double
    //How to do both conversion Ownership to JSON String, 
    //    but MeanInterval (TimeSpan) needs to be converted to long (Ticks) too!
    
}

我知道我需要使用该HasConversion()方法,但我不知道具体该怎么做!

我将如何实现(或使用)HasConversion(Ownership到 JSON 字符串和MeanInterval长)?

4

1 回答 1

0

我认为你可以使用这个

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<Owner>()
                .Property(o => o.Ownership)
                .HasConversion<string>(o => JsonConvert.SerializeObject(o),
                db => JsonConvert.DeserializeObject<Ownership>(db));
        }

在这种情况下,您必须使用 Newtonsoft.Json Nuget 包将对象序列化为 Ownership 类的 json 字符串,HasConversion() 方法具有允许放置 ToFormatter 和 FromFormatter 以避免创建 ValueConverter 对象的重载,请检查此https: //docs.microsoft.com/en-us/ef/core/modeling/value-conversions如果您想了解有关此转换的更多信息。

于 2021-02-06T02:25:24.227 回答