EF Core删除带有空值的子级

时间:2020-10-23 06:59:56

标签: asp.net-core entity-framework-core

下面是我的分层模型

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>();
}

查询:

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

查询工作正常:如何排除没有子元素的菜单

请在下面检查。

enter image description here

我已添加配置

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

但是在json文件中它会出现..是否可以在ef核心本身中排除?我正在使用最新的EF核心预览。

编辑: EF本身计数为0表示..如何避免使用count = 0?

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在为Children属性分配默认值,这就是为什么您总是在响应中看到它的原因。要解决此问题,只需将= new List<MenuModel>();更改为= null!;

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