Skip to content Skip to sidebar Skip to footer

Storing Custom Class Property Like String Via Onmodelcreating Of Dbcontext .net Core

I have two classes in .Net Core The class Owner namespace CustomStoreDatabase.Models { public class Owner { public string OwnerId { get; set; } public DateT

Solution 1:

I think that you can use this

protected override voidOnModelCreating(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.

Post a Comment for "Storing Custom Class Property Like String Via Onmodelcreating Of Dbcontext .net Core"