I have base
class as follow
[DataContract]
public class BaseTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Created { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? Updated { get; set; }
}
Here is my parent
class
[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; }
}
Here is Child
class
[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; }
}
Here is GrandChild
Class
[DataContract]
public class GrandChild:BaseTable
{
[Required]
[DataMember(Name = "key")]
[Key]
public Guid Key { get; set; }
[Required]
[DataMember(Name = "name")]
public string Name { get; set; }
}
Here is my Controller API method
[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);
}
I see all the proper values inside result
while debugging.
But, returned JSON has null
values for child entities.!!
Anything I am missing?
How can I map these multiple objects to single DTO?
I have created mapping like this
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)))
Still not working
A suitable method for this situation is convert your retsult data to a string by JsonConvert method:
string stItems = JsonConvert.SerializeObject(result, Formatting.Indented,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return ok(stItems);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.