Created
May 2, 2018 06:25
-
-
Save yorek/587616768e2a12054403b68762682ace to your computer and use it in GitHub Desktop.
Return a single JSON from SQL Server and map it into a custom object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Data.SqlClient; | |
using Dapper; | |
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
namespace stackoverflow_dapper_50091943 | |
{ | |
public class City | |
{ | |
public int CityId; | |
public string CityName; | |
} | |
public class Country { | |
public int CountryId; | |
public string CountryName; | |
public List<City> Cities = new List<City>(); | |
} | |
public class Continent | |
{ | |
public int ContinentId; | |
public string ContinentName; | |
public List<Country> Countries = new List<Country>(); | |
} | |
class Program | |
{ | |
public class ContinentTypeHandler : SqlMapper.TypeHandler<List<Continent>> | |
{ | |
// Handles how data is deserialized into object | |
public override List<Continent> Parse(object value) | |
{ | |
return JsonConvert.DeserializeObject<List<Continent>>(value.ToString()); | |
} | |
// Handles how data is saved into the database | |
public override void SetValue(IDbDataParameter parameter, List<Continent> value) | |
{ | |
parameter.Value = null; | |
} | |
} | |
static void Main(string[] args) | |
{ | |
SqlMapper.ResetTypeHandlers(); | |
SqlMapper.AddTypeHandler(new ContinentTypeHandler()); | |
using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB; Initial Catalog=tempdb;")) | |
{ | |
var result = conn.QuerySingle<List<Continent>>("dbo.GetContinentsDetail", commandType: CommandType.StoredProcedure); | |
result.ForEach(c => { | |
Console.WriteLine(JsonConvert.SerializeObject(c)); | |
Console.WriteLine(); | |
}); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment