我必须在 DbContext 中添加哪些配置来存储 IDictionary 类型的属性<string, object>

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

我的代码中有一个域实体,其中我有属性

Parameters
,其类型为
Dictionary<string, object>
。我尝试添加
JsonConvert
。但是数据在存储到数据库时会发生变化。

任务.cs

public sealed class Task
{
    
    public Guid TaskId { get; set; }
    public Guid QueryId { get; set; }
    public Guid DatabaseId { get; set; }
    public Guid OrganizationId { get; set; }
    public DateTime CreatedOn = DateTime.UtcNow;
    public string Status { get; set; } = string.Empty;
    public IDictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
}

DbContext.cs

public interface IDbContext
{
    DbSet<Task> Tasks { get; }
    Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess = true, CancellationToken cancellationToken = default);
}

internal sealed class QueryHubDbContext : DbContext, IQueryHubDbContext
{
    public QueryHubDbContext(DbContextOptions<QueryHubDbContext> options)
        : base(options)
    {
    }
    public DbSet<Task> Tasks => Set<Task>();
   

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Query>(entity =>
        {
            entity.Property(e => e.Id).ValueGeneratedNever();
            entity.Property(e => e.Tags)
            .HasConversion(
                v => string.Join(',', v.Where(tag => !string.IsNullOrWhiteSpace(tag))),
                v => v.Split(',', StringSplitOptions.RemoveEmptyEntries));
        });

        modelBuilder.Entity<Task>(ConfigureTask);

        base.OnModelCreating(modelBuilder);
    }

    private void ConfigureTask(EntityTypeBuilder<Task> builder)
    {
        builder.HasKey(e => e.TaskId);
        builder.Property(e => e.TaskId).ValueGeneratedNever();
         builder.Property(e => e.Parameters)
            .HasConversion(
                v => JsonConvert.SerializeObject(v),
                v => JsonConvert.DeserializeObject<Dictionary<string, object>>(v) ?? new Dictionary<string, object>())
            .HasColumnType("nvarchar(max)");
    }
}

当我通过这些配置时

{
  "taskId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "queryId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "databaseId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "status": "string",
  "parameters": {
    "additionalProp1": "string",
    "additionalProp2": "string",
    "additionalProp3": "string"
  }
}

数据库中存储的数据 ->


{
  "taskId": "9abf0000-76ab-40b0-d1d5-08dbf0421eaa",
  "queryId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "databaseId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "organizationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "status": "",
  "parameters": {
    "additionalProp1": {
      "valueKind": []
    },
    "additionalProp2": {
      "valueKind": []
    },
    "additionalProp3": {
      "valueKind": []
    }
  }
}

我使用 SqlServer 作为我的数据库。 postgres 存在一个数据库类型“json”或“jsonb”。 sql server 没有。

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

我测试通过了有一些差异的数据,没有问题。
任务.cs

    public class Task
    {
        [Key]
        public int Id { get; set; }
        public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
    }

MyContext.cs

    public class MyContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql("server=192.168.2.68;database=wa76;user=mysql1;password=xxxxx", new MySqlServerVersion(new Version()));
        }

        public DbSet<Task> TaskTable { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Task>()
                .Property(b => b.Parameters)
                .HasConversion(
                    v => JsonConvert.SerializeObject(v),
                    v => JsonConvert.DeserializeObject<Dictionary<string, object>>(v));
        }
    }

控制器

        [HttpPost("test")]
        public void test(object obj)
        {
            var model = JsonConvert.DeserializeObject<Task>(obj.ToString());
            _context.Add(model);
            _context.SaveChanges();
        }

测试
邮递员:

结果:

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