【问题标题】:Mapping multiple table to single DTO in.Entity Framework Core - Some properties are not rendering in JSON output在.Entity Framework Core 中将多个表映射到单个 DTO - 某些属性未在 JSON 输出中呈现
【发布时间】:2026-02-10 03:35:01
【问题描述】:

我有base 类如下

 [DataContract]
 public class BaseTable
 {        
     [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
     public DateTime? Created { get; set; }

     [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
     public DateTime? Updated { get; set; }
 }

这是我的parent 课程

 [DataContract]
 public class Parent:BaseTable
 {
    [Required]
    [DataMember(Name = "key")]
    [Key]
    public Guid Key { get; set; }

    [Required]
    [DataMember(Name = "name")]
    public string Name { get; set; }

    [DataMember(Name = "Child")]
    public virtual ICollection<Child> Children{ get; set; }
 }

这里是Child

[DataContract]
public class Child:BaseTable
{
    [Required]
    [DataMember(Name = "key")]
    [Key]
    public Guid Key { get; set; }

    [ForeignKey("ParentKey")]
    [IgnoreDataMember]
    public virtual Parent Parent{ get; set; }

    public Guid GrandChildKey { get; set; }

    [ForeignKey("GrandChildKey")]
    public virtual GrandChild GrandChild { get; set; }

 }

这里是GrandChild

[DataContract]
public class GrandChild:BaseTable
{
    [Required]
    [DataMember(Name = "key")]
    [Key]
    public Guid Key { get; set; }

    [Required]
    [DataMember(Name = "name")]
    public string Name { get; set; }
 }

这是我的控制器 API 方法

    [HttpGet]
    [Route("parentgroups")]
    [Produces("application/json")]
    [SwaggerOperation("GetSupportedParentGroups")]
    [SwaggerResponse(400, "Bad input parameter")]
    [SwaggerResponse(404, "Not found")]
    [SwaggerResponse(500, "Internal server error")]
    [ProducesResponseType(200, Type = typeof(Parent))]
    public async Task<IActionResult> GetParentGroups()
    {
             var result = await _context.Parents
             .Include(b => b.Children)
              .ThenInclude(children=> children.GrandChild)
                   .ToListAsync();

             return Ok(result);
    }

我在调试时看到 result 中的所有正确值。

但是,返回的 JSON 包含子实体的 null 值。!!

我缺少什么吗?

如何将这些多个对象映射到单个 DTO?

我已经创建了这样的映射

         CreateMap<ParentDto, Parent>()
            .ForMember(d => d.Key, opt => opt.MapFrom(s => s.Key))
            .ForMember(d => d.Name, opt => opt.MapFrom(s => s.Name))
            .ForMember(d => d.Children, opt => opt.MapFrom(s => Mapper.Map<ParentDto, Child>(s)))

还是不行

【问题讨论】:

    标签: c# entity-framework entity-framework-6 automapper


    【解决方案1】:

    适合这种情况的方法是通过 JsonConvert 方法将结果数据转换为字符串:

      string stItems = JsonConvert.SerializeObject(result, Formatting.Indented,
            new JsonSerializerSettings
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
            return ok(stItems);
    

    【讨论】: