You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core下StudentDto与StudentEntity的Columns属性映射问题

解决方法

1. 手动映射(无需第三方库)

直接在Dto转Entity的逻辑里处理Columns的序列化,判断列表为空时存入NULL,否则转为JSON字符串:

示例代码(System.Text.Json)

using System.Text.Json;

// 转换逻辑
var studentEntity = new StudentEntity
{
    // 映射其他属性
    Columns = studentDto.Columns?.Any() == true 
        ? JsonSerializer.Serialize(studentDto.Columns) 
        : null
};

示例代码(Newtonsoft.Json)

如果项目用Newtonsoft.Json:

using Newtonsoft.Json;

var studentEntity = new StudentEntity
{
    // 映射其他属性
    Columns = studentDto.Columns?.Any() == true 
        ? JsonConvert.SerializeObject(studentDto.Columns) 
        : null
};

2. AutoMapper全局映射配置

如果项目依赖AutoMapper,可以在Profile中定义专属映射规则,统一处理Columns属性:

using AutoMapper;
using System.Text.Json;

public class StudentProfile : Profile
{
    public StudentProfile()
    {
        CreateMap<StudentDto, StudentEntity>()
            .ForMember(dest => dest.Columns, opt => opt.MapFrom(src => 
                src.Columns?.Any() == true 
                    ? JsonSerializer.Serialize(src.Columns) 
                    : null));
    }
}

之后直接用Mapper转换:

var studentEntity = _mapper.Map<StudentEntity>(studentDto);

3. EF Core实体配置(双重保障)

为了避免映射遗漏,可以在EF Core的实体配置中添加ValueConverter,确保写入数据库时自动处理转换逻辑:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.Text.Json;

public class StudentEntityConfiguration : IEntityTypeConfiguration<StudentEntity>
{
    public void Configure(EntityTypeBuilder<StudentEntity> builder)
    {
        builder.Property(e => e.Columns)
            .HasConversion(
                // 写入数据库:List<string>转JSON或NULL
                v => 
                {
                    if (v == null || !v.Any())
                        return null;
                    return JsonSerializer.Serialize(v);
                },
                // 读取数据库:JSON转List<string>
                v => 
                {
                    if (string.IsNullOrEmpty(v))
                        return new List<string>();
                    return JsonSerializer.Deserialize<List<string>>(v) ?? new List<string>();
                }
            );
    }
}

在DbContext中应用配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyConfiguration(new StudentEntityConfiguration());
}

注意事项

  • 若偏好Newtonsoft.Json,替换序列化/反序列化方法即可。
  • 可通过JsonSerializerOptions调整JSON格式,比如添加WriteIndented = false取消缩进。

内容的提问来源于stack exchange,提问作者atalay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:32:35