通过 DBContext .Net Core 的 OnModelCreating 存储自定义 class 属性 之类的字符串

Storing custom class property like String via OnModelCreating of DBContext .Net Core

我在 .Net Core 中有两个 classes

classOwner

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

还有 class 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 这样的所有权 class 和像 long 这样的 MeanInterval 在数据库中存储。 我正在检查 and this,但我不明白如何应用它。

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 到长)?

我觉得你可以用这个

        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 包将对象序列化为 json 所有权字符串 class,HasConversion() 方法有一个重载,允许将ToFormatter 和 FromFormatter 以避免创建 ValueConverter 对象,如果您想了解有关此转换的更多信息,请检查此 https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions