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

查看:189
本文介绍了如何使用 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 Core Value Conversions 的回答(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天全站免登陆