在实体框架核心中将多个表映射到单个DTO-某些属性未在JSON输出中呈现

时间:2019-01-07 08:31:02

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

我有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; }
 }

这是我的Controller 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)))

仍然无法正常工作

1 个答案:

答案 0 :(得分:0)

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

R r = new R();
new ConstructorRefVsNew().run(r::run);