问题描述
.Net Core中有两个类
I have two classes in .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像这样存储在数据库中.我正在检查此和这,但我不知道该如何应用.
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!
}
我知道我需要使用 HasConversion()
方法,但是我不知道该怎么做!
I know that I need to use the HasConversion()
method, but I don't know exactly how to do it!
我将如何实现(或使用)HasConversion(将所有权转换为JSON字符串,将 MeanInterval
转换为long)?
How I would to implement (or use) the HasConversion (Ownership
to JSON String and MeanInterval
to long)?
推荐答案
我认为您可以使用此
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/zh-CN/ef/core/modeling/value-conversions ,如果您想了解更多有关此转换的信息.
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.
这篇关于通过DBContext .Net Core的OnModelCreating存储诸如String之类的自定义类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!