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

681 views Asked by At

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

There are 1 answers

1
jann moreno On BEST ANSWER

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://learn.microsoft.com/en-us/ef/core/modeling/value-conversions if you want to know more about this conversions.