Glen
Glen

Reputation: 331

Ef core remove child with null

Below is my Hierarchical model

public class MenuModel
{
    public int Id { get; set; }
    public string Name { get; set; } = null!;
    public string? Url { get; set; } = null!;
    public string? Icon { get; set; }
    public int? ParentId { get; set; }
    public MenuModel Parent { get; set; } = null!;
    public ICollection<MenuModel>? Children { get; set; } = new List<MenuModel>();
}

Query:

return await _context.Menus//.Include(o => o.Parent)
                             .Include(m => m.Childrens)
                             .ThenInclude(m => m.Childrens)
                             .Where(m => m.ParentId == null)
                             .ToListAsync();

Query is working fine: How to exclude menu without child elements

Please check below..

enter image description here

I have Added in configuration

services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    })
    .AddJsonOptions(options => {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

But in json file it coming.. Is it possible to exclude in ef core itself? I am using latest EF core preview.

EDIT: Ef itself count with 0 showing ..How avoid with count=0?

enter image description here

Upvotes: 0

Views: 175

Answers (1)

M&#233;toule
M&#233;toule

Reputation: 14472

You're assigning a default value to the Children property, which is why you always see it in your response. To fix this, simply change the = new List<MenuModel>(); to = null!;

public class MenuModel
{
    ...
    public ICollection<MenuModel>? Children { get; set; } = null!;
}

Upvotes: 1

Related Questions