如何使用EF Core将JSON存储在实体字段中? [英] How to store JSON in an entity field with EF Core?

查看:568
本文介绍了如何使用EF Core将JSON存储在实体字段中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET Core(针对.NETStandard 1.4)创建可重用的库,并且正在使用Entity Framework Core(这两者都是新的).我有一个看起来像这样的实体类:

I am creating a reusable library using .NET Core (targeting .NETStandard 1.4) and I am using Entity Framework Core (and new to both). I have an entity class that looks like:

public class Campaign
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }

    public JObject ExtendedData { get; set; }
}

,并且我有一个定义DbSet的DbContext类:

and I have a DbContext class that defines the DbSet:

public DbSet<Campaign> Campaigns { get; set; }

(我也在DI上使用Repository模式,但我认为这不相关.)

(I am also using the Repository pattern with DI, but I don't think that is relevant.)

我的单元测试给我这个错误:

My unit tests give me this error:

System.InvalidOperationException:无法确定关系 由类型的导航属性"JToken.Parent"表示 'JContainer'.手动配置关系,或者忽略 该属性来自模型.

System.InvalidOperationException: Unable to determine the relationship represented by navigation property 'JToken.Parent' of type 'JContainer'. Either manually configure the relationship, or ignore this property from the model..

有没有办法表明这不是关系但应该存储为大字符串?

Is there a way to indicate that this is not a relationship but should be stored as a big string?

推荐答案

@Michael的回答使我步入正轨,但我在实现上有所不同.我最终将值作为字符串存储在私有属性中,并将其用作背景字段".然后,ExtendedData属性在set上将JObject转换为字符串,在get上将其转换为字符串.

@Michael's answer got me on track but I implemented it a little differently. I ended up storing the value as a string in a private property and using it as a "Backing Field". The ExtendedData property then converted JObject to a string on set and vice versa on get:

public class Campaign
{
    // https://docs.microsoft.com/en-us/ef/core/modeling/backing-field
    private string _extendedData;

    [Key]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Name { get; set; }

    [NotMapped]
    public JObject ExtendedData
    {
        get
        {
            return JsonConvert.DeserializeObject<JObject>(string.IsNullOrEmpty(_extendedData) ? "{}" : _extendedData);
        }
        set
        {
            _extendedData = value.ToString();
        }
    }
}

要将_extendedData设置为后备字段,我将其添加到上下文中:

To set _extendedData as a backing field, I added this to my context:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Campaign>()
        .Property<string>("ExtendedDataStr")
        .HasField("_extendedData");
}

更新:达伦(Darren)使用EF核心价值转换的答案(是EF Core 2.1的新功能-在此答案发布之时尚不存在)似乎是此时的最佳选择.

Update: Darren's answer to use EF Core Value Conversions (new to EF Core 2.1 - which didn't exist at the time of this answer) seems to be the best way to go at this point.

这篇关于如何使用EF Core将JSON存储在实体字段中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆