O mesmo de cima, um pouco mais detalhado
Usando o .Net Core
Controlador
public class TestController : Controller
{
private string connectionString;
public IDbConnection Connection
{
get { return new SqlConnection(connectionString); }
}
public TestController()
{
connectionString = @"Data Source=OCIUZWORKSPC;Initial Catalog=SocialStoriesDB;Integrated Security=True";
}
public JsonResult GetEventCategory(string q)
{
using (IDbConnection dbConnection = Connection)
{
var categories = dbConnection.Query<ResultTokenInput>("GetEventCategories", new { keyword = q },
commandType: CommandType.StoredProcedure).FirstOrDefault();
return Json(categories);
}
}
public class ResultTokenInput
{
public int ID { get; set; }
public string name { get; set; }
}
}
Procedimento armazenado (relação pai-filho)
create PROCEDURE GetEventCategories
@keyword as nvarchar(100)
AS
BEGIN
WITH CTE(Id, Name, IdHierarchy,parentId) AS
(
SELECT
e.EventCategoryID as Id, cast(e.Title as varchar(max)) as Name,
cast(cast(e.EventCategoryID as char(5)) as varchar(max)) IdHierarchy,ParentID
FROM
EventCategory e where e.Title like '%'+@keyword+'%'
-- WHERE
-- parentid = @parentid
UNION ALL
SELECT
p.EventCategoryID as Id, cast(p.Title + '>>' + c.name as varchar(max)) as Name,
c.IdHierarchy + cast(p.EventCategoryID as char(5)),p.ParentID
FROM
EventCategory p
JOIN CTE c ON c.Id = p.parentid
where p.Title like '%'+@keyword+'%'
)
SELECT
*
FROM
CTE
ORDER BY
IdHierarchy
Referências no caso
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using SocialStoriesCore.Data;
using Microsoft.EntityFrameworkCore;
using Dapper;
using System.Data;
using System.Data.SqlClient;