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

孤人 提交于 2021-02-11 12:22:22

问题


I have two classes in .Net Core

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

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

Now, I want to store like String the Ownership class, and MeanInterval like long in the Database. I was checking this and this, But I don't understand how apply it.

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

I know that I need to use the HasConversion() method, but I don't know exactly how to do it!

How I would to implement (or use) the HasConversion (Ownership to JSON String and MeanInterval to long)?


回答1:


I think that you can use this

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

in this case you must use Newtonsoft.Json Nuget package to serialize the object as a json string of Ownership class, the HasConversion() method has an overload that allows to put the ToFormatter and FromFormatter to avoid creating a ValueConverter object, check this https://docs.microsoft.com/en-us/ef/core/modeling/value-conversions if you want to know more about this conversions.



来源:https://stackoverflow.com/questions/66072157/storing-custom-class-property-like-string-via-onmodelcreating-of-dbcontext-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!