Entity Framework .NET 8 将数据保存为 JSON 对象

问题描述 投票:0回答:1

我想像这样在 SQL Server 中保存数据:

Preparation : 
    [
        "reviewCustomerDataBeforeVisit": "5", 
        "setSmartObjectivesForVisit": "5",          
        "complaintHandlingPlan": "5"
    ]
  • 可能吗?
  • 或者还有其他办法吗?
  • 或者,在代码优先中,我应该做什么?

这是我的实体:

namespace Msfa.Api.Entities
{
    public class InfieldCoaching
    {
        public int Id { get; set; }
        public string? InfieldCoachingId { get; set; }
        public Preparation Preparation { get; set; }
        public Opening Opening { get; set; }
        public DateTime? CreatedTime { get; set; }
        public DateTime? UpdatedTime { get; set; }
    }

    public class Preparation
    {
        [Range(1, 5)]
        public int? ReviewCustomerDataBeforeVisit { get; set; }
        [Range(1, 5)]
        public int? SetSmartObjectivesForVisit { get; set; }
        [Range(1, 5)]
        public int? ComplaintHandlingPlan { get; set; }
    }

    public class Opening
    {
        [Range(1, 5)]
        public int? CreateCustomerAttention { get; set; }
        [Range(1, 5)]
        public int? ProductVisibilityChecked { get; set; }
        [Range(1, 5)]
        public int? StockLevelsCounted { get; set; }
    }
}

这是我基于该实体从 Swagger 发出的

POST
请求:

{
  "preparation": {
    "reviewCustomerDataBeforeVisit": 5,
    "setSmartObjectivesForVisit": 5,
    "complaintHandlingPlan": 5
  },
  "opening": {
    "createCustomerAttention": 5,
    "productVisibilityChecked": 5,
    "stockLevelsCounted": 5
  },
  "managers": [
    "string"
  ]
} 

如何实现这一目标?

asp.net-core entity-framework-core .net-8.0
1个回答
0
投票

基于此解决方案入门:Entity Framework Core 7 JSON 支持

我将这些添加到

ApplicationDbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<InfieldCoaching>()
        .OwnsOne(p => p.Preparation, builder => { builder.ToJson(); })
        .OwnsOne(p => p.Opening, builder => { builder.ToJson(); });
}

使用:EntityFrameworkCore 8.0.0

© www.soinside.com 2019 - 2024. All rights reserved.