You'll need two classes to hold your data:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public string NFacts_Energy { get; set; }
public string NFacts_TotalFat { get; set; }
public string NFacts_TotalCarb { get; set; }
public string NFacts_Proteins { get; set; }
public string NFacts_Sugars { get; set; }
public string CookingInstructions { get; set; }
public IList<SubProduct> subproduct { get; } = new List<SubProduct>();
}
public class SubProduct
{
public int Id { get; set; }
public string Name { get; set; }
public int ProductId { get; set; }
public string Weight { get; set; }
public decimal Price { get; set; }
}
You then need to load the data -
Dapper[
^] makes this fairly easy:
const string query = "SELECT * FROM [tbl_Product] WHERE isactive = 0;
SELECT * FROM [tbl_ProductDetails] WHERE isactive = 0;";
using (var connection = new SqlConnection(...))
{
List<Product> products;
using (var multi = connection.QueryMultiple(query))
{
products = multi.Read<Product>().ToList();
var subproducts = multi.Read<SubProduct>().ToLookup(sp => sp.ProductId);
foreach (var product in products)
{
foreach (var subproduct in subproducts[product.id])
{
product.subproduct.Add(subproduct);
}
}
}
...
}
EDIT: Not quite as simple as I thought. If you use the "multi-mapping" option, you end up with one
Product
record for each row in the results. You have to use the "multiple results" option for a one-to-many query.
Then you need to convert the list of products to JSON.
Json.NET[
^] is probably the best way to do that:
string json = JsonConvert.SerializeObject(products, Formatting.Indented);