Asp.net core 我有一个sql server分层数据表,其中包含以下示例结构和数据:
我的表格结构是:Asp.net core 我有一个sql server分层数据表,其中包含以下示例结构和数据:,asp.net-core,sql-server-2012,primeng-datatable,Asp.net Core,Sql Server 2012,Primeng Datatable,我的表格结构是: Id name size type parrent_Id 1 AAAA 2k t1 null 2 BB 2k t2 1 3 CC 1k t3 1 4 DDDD 2k t4 null 5 EE 2k t5
Id name size type parrent_Id
1 AAAA 2k t1 null
2 BB 2k t2 1
3 CC 1k t3 1
4 DDDD 2k t4 null
5 EE 2k t5 4
6 FF 1k t6 5
我需要一个从表生成JSON结构的SQL查询,以便在初始化树表组件时使用它。它需要这样的JSON结构。iam在sql server上使用asp.net核心web api:
{
"data":
[
{
"data":{
"name":"Documents",
"size":"2k",
"type":"Folder"
},
"children":[
{
"data":{
"name":"Work",
"size":"5k",
"type":"Folder"
},
]
}
]
假设您使用的是
EF-Core
,您的模型如下所示:
public class XModel {
public int Id {get;set;}
public string Name {get;set;}
public string Size {get;set;}
public string Type {get;set;}
public int? ParentId {get;set;}
public XModel Parent {get;set;}
public IList<XModel> Children {get;set;}
}
让我们构建一个扩展方法来构建树
public static class TreeLikeExtensions
{
public static IList<Dto> BuildTrees(this IQueryable<XModel> models)
{
var dtos = models.Select(m =>new Dto{
Data = new Data { Id = m.Id, Name = m.Name, Size =m.Size, Type = m.Type, ParentId = m.ParentId, },
Children = null,
}).ToList();
return BuildTrees(null, dtos);
}
// private helper function that builds tree recursively
private static IList<Dto> BuildTrees(int? pid, IList<Dto> candicates)
{
var children = candicates.Where(c => c.Data.ParentId == pid).ToList();
if (children==null || children.Count() == 0){
return null;
}
foreach (var i in children){
i.Children= BuildTrees(i.Data.Id, candicates);
}
return children;
}
}
要在序列化时忽略null
children属性,只需添加如下设置:
// var settings= new JsonSerializerSettings{
// NullValueHandling = NullValueHandling.Ignore,
// ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
// }
或者在Startup.cs
中配置MVC系列:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(o =>{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});
工作演示
您正在使用ASP.NET Core吗?您需要更具体地回答您的问题,并提供更多详细信息。我正在使用asp.net core和sql Server检查ITS提供的答案
// var settings= new JsonSerializerSettings{
// NullValueHandling = NullValueHandling.Ignore,
// ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
// }
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(o =>{
o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});