Skip to content

Commit ab8b86b

Browse files
authored
Merge pull request microsoft#185 from JocaPC/master
Added JSON in Entity Framework
2 parents f4ea23e + 615c903 commit ab8b86b

File tree

98 files changed

+25233
-192
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

98 files changed

+25233
-192
lines changed

media/features/json-in-table.png

27.1 KB
Loading

samples/demos/belgrade-product-catalog-demo/.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ obj/*
88
*.lock.json
99
Properties/PublishProfiles/*
1010
appsettings.Development.json
11-
appsettings.Production.json
11+
appsettings.Production.json
12+
*.ndjson

samples/demos/belgrade-product-catalog-demo/Controllers/CompanyController.cs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,21 @@ public async Task Get()
2828
[HttpGet("login")]
2929
public void Login(string id)
3030
{
31-
try
31+
if(id=="0")
32+
ControllerContext.HttpContext.Session.Remove("CompanyID");
33+
else
34+
ControllerContext.HttpContext.Session.SetString("CompanyID", id);
35+
string referer;
36+
switch (Request.Query["page"])
3237
{
33-
if(id=="0")
34-
ControllerContext.HttpContext.Session.Remove("CompanyID");
35-
else
36-
ControllerContext.HttpContext.Session.SetString("CompanyID", id);
37-
Response.Redirect("/index.html");
38-
} catch (Exception ex)
39-
{
40-
Response.WriteAsync(ex.Message);
38+
case "index": referer = "/index.html"; break;
39+
case "report1": referer = "/report-pie.html"; break;
40+
case "report2": referer = "/report-multibar.html"; break;
41+
case "dashboard": referer = "/dashboard.html"; break;
42+
case "temporal": referer = "/temporal.html"; break;
43+
default: referer = "/index.html"; break;
4144
}
45+
Response.Redirect(referer);
4246
}
4347
}
4448
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using ProductCatalog.Models;
3+
using System;
4+
using System.Linq;
5+
6+
namespace ProductCatalog.Controllers
7+
{
8+
public class ProductCatalogController : Controller
9+
{
10+
private ProductCatalogContext _context;
11+
12+
public ProductCatalogController (ProductCatalogContext context)
13+
{
14+
_context = context;
15+
}
16+
17+
[HttpGet]
18+
public IActionResult Index()
19+
{
20+
ViewData["page"] = "index";
21+
return View(_context.Products.AsEnumerable());
22+
}
23+
24+
// POST api/ProductCatalog/Add
25+
public IActionResult Add(Product p)
26+
{
27+
try
28+
{
29+
_context.Products.Add(p);
30+
_context.SaveChanges();
31+
return Redirect("/ProductCatalog/Index");
32+
} catch (Exception)
33+
{
34+
return Redirect("/ProductCatalog/Index");
35+
}
36+
}
37+
38+
public IActionResult Report1()
39+
{
40+
ViewData["page"] = "report1";
41+
return View();
42+
}
43+
44+
public IActionResult Report2()
45+
{
46+
ViewData["page"] = "report2";
47+
return View();
48+
}
49+
}
50+
}

samples/demos/belgrade-product-catalog-demo/Controllers/ProductController.cs

Lines changed: 56 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
using Belgrade.SqlClient;
22
using Microsoft.AspNetCore.Mvc;
3+
using Microsoft.Extensions.Logging;
34
using System;
45
using System.Data.SqlClient;
56
using System.IO;
6-
using System.Text;
77
using System.Threading.Tasks;
88

99
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
@@ -16,18 +16,28 @@ public class ProductController : Controller
1616
IQueryPipe sqlQuery = null;
1717
ICommand sqlCmd = null;
1818
private readonly string EMPTY_PRODUCTS_ARRAY = "{\"data\":[]}";
19-
private readonly byte[] EMPTY_PRODUCTS_ARRAY_GZIPPED = new byte[] {0x1F,0x8B,0x08,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0xAB,0x66,0x50,0x62,0x48,0x61,0x48,0x64,0x28,0x01,0x62,0x25,0x06,0x2B,0x86,0x68,0x86,0x58,0x86,0x5A,0x06,0x00,0xB3,0x4C,0x62,0xB2,0x16,0x00,0x00,0x00};
19+
private readonly byte[] EMPTY_PRODUCTS_ARRAY_GZIPPED = new byte[] { 0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0xAB, 0x66, 0x50, 0x62, 0x48, 0x61, 0x48, 0x64, 0x28, 0x01, 0x62, 0x25, 0x06, 0x2B, 0x86, 0x68, 0x86, 0x58, 0x86, 0x5A, 0x06, 0x00, 0xB3, 0x4C, 0x62, 0xB2, 0x16, 0x00, 0x00, 0x00 };
20+
private readonly ILogger logger;
2021

21-
public ProductController(IQueryPipe sqlQueryService, ICommand sqlCommandService)
22+
public ProductController(IQueryPipe sqlQueryService, ICommand sqlCommandService, ILogger<ProductController> logger)
2223
{
2324
this.sqlQuery = sqlQueryService;
2425
this.sqlCmd = sqlCommandService;
26+
this.logger = logger;
2527
}
2628

2729
// GET api/Product
2830
public async Task Get()
2931
{
30-
await sqlQuery.Stream(@"
32+
await sqlQuery
33+
.OnError(
34+
ex =>
35+
{
36+
logger.LogError("Error while trying to get products: {Error}\n{StackTrace}", ex.Message, ex.StackTrace);
37+
this.Response.StatusCode = 500;
38+
throw ex;
39+
})
40+
.Stream(@"
3141
select ProductID, Name, Color, Price, Quantity,
3242
JSON_VALUE(Data, '$.MadeIn') as MadeIn, JSON_QUERY(Tags) as Tags
3343
from Product
@@ -64,7 +74,7 @@ from Product
6474
cmd.Parameters.AddWithValue("id", id);
6575
await sqlQuery.Stream(cmd, Response.Body, "{}");
6676
}
67-
77+
6878
// POST api/Product
6979
[HttpPost]
7080
public async Task Post()
@@ -116,7 +126,47 @@ public void RestoreVersion(int ProductId, DateTime DateModified)
116126
var cmd = new SqlCommand("EXEC RestoreProduct @productid, @date");
117127
cmd.Parameters.AddWithValue("@productid", ProductId);
118128
cmd.Parameters.AddWithValue("@date", DateModified);
119-
this.sqlCmd.ExecuteNonQuery(cmd);
129+
this.sqlCmd
130+
.OnError(
131+
ex =>
132+
{
133+
logger.LogError("Error while trying to restore product with id {ProductID} from time {DateModified}.\n{Error}\n{StackTrace}", ProductId, DateModified, ex.Message, ex.StackTrace);
134+
this.Response.StatusCode = 500;
135+
throw ex;
136+
})
137+
.ExecuteNonQuery(cmd);
138+
}
139+
140+
141+
[HttpGet("Report1")]
142+
[Produces("application/json")]
143+
public async Task Report1()
144+
{
145+
await sqlQuery
146+
.Stream(@"
147+
select color as x, sum(quantity) as y
148+
from product
149+
where color is not null
150+
group by color
151+
for json path", Response.Body, EMPTY_PRODUCTS_ARRAY);
152+
}
153+
154+
155+
[HttpGet("Report2")]
156+
[Produces("application/json")]
157+
public async Task Report2()
158+
{
159+
await sqlQuery
160+
.Stream(@"
161+
select name as [key], [values].x, [values].y
162+
from company
163+
join (select companyid, color as x, sum(quantity) as y
164+
from product
165+
where color is not null
166+
group by companyid, color
167+
) as [values] on company.companyid = [values].companyid
168+
order by company.companyid
169+
for json auto", Response.Body, EMPTY_PRODUCTS_ARRAY);
120170
}
121171
}
122172
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using Newtonsoft.Json;
3+
using System.Collections.Generic;
4+
using System.ComponentModel.DataAnnotations;
5+
using System.ComponentModel.DataAnnotations.Schema;
6+
7+
namespace ProductCatalog.Models
8+
{
9+
[Table("Product")]
10+
public class Product
11+
{
12+
public int ProductId { get; set; }
13+
14+
public string Name { get; set; }
15+
16+
public string Color { get; set; }
17+
18+
public string Size { get; set; }
19+
20+
public decimal Price { get; set; }
21+
22+
public int Quantity { get; set; }
23+
24+
public int CompanyID { get; set; }
25+
26+
[NotMapped]
27+
public string[] Tags
28+
{
29+
get { return _Tags == null ? null : JsonConvert.DeserializeObject<string[]>(_Tags); }
30+
set { _Tags = JsonConvert.SerializeObject(value); }
31+
}
32+
33+
internal string _Tags { get; set; }
34+
35+
[NotMapped]
36+
public Properties Data
37+
{
38+
get { return (this._Data == null) ? null : JsonConvert.DeserializeObject<Properties>(this._Data); }
39+
set { _Data = JsonConvert.SerializeObject(value); }
40+
}
41+
42+
internal string _Data { get; set; }
43+
}
44+
45+
public class Properties
46+
{
47+
public string Type { get; set; }
48+
49+
public string MadeIn { get; set; }
50+
}
51+
52+
public class ProductCatalogContext : DbContext
53+
{
54+
public ProductCatalogContext(DbContextOptions<ProductCatalogContext> options)
55+
: base(options)
56+
{ }
57+
58+
protected override void OnModelCreating(ModelBuilder modelBuilder)
59+
{
60+
modelBuilder.Entity<Product>()
61+
.Property(x => x.ProductId)
62+
.HasDefaultValueSql("NEXT VALUE FOR ProductId");
63+
64+
modelBuilder.Entity<Product>()
65+
.Property(b => b._Tags).HasColumnName("Tags");
66+
67+
modelBuilder.Entity<Product>()
68+
.Property(b => b._Data).HasColumnName("Data");
69+
}
70+
71+
public DbSet<Product> Products { get; set; }
72+
}
73+
74+
}

samples/demos/belgrade-product-catalog-demo/ProductCatalog.xproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
88
<PropertyGroup Label="Globals">
99
<ProjectGuid>7e230e5a-b0b6-4f56-9561-942fd1817b80</ProjectGuid>
10-
<RootNamespace>product_catalog</RootNamespace>
10+
<RootNamespace>ProductCatalog</RootNamespace>
1111
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
1212
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
1313
<TargetFrameworkVersion>v4.6</TargetFrameworkVersion>

samples/demos/belgrade-product-catalog-demo/Properties/launchSettings.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,15 @@
1111
"IIS Express": {
1212
"commandName": "IISExpress",
1313
"launchBrowser": true,
14-
"launchUrl": "index.html",
14+
"launchUrl": "ProductCatalog/Index",
1515
"environmentVariables": {
1616
"ASPNETCORE_ENVIRONMENT": "Development"
1717
}
1818
},
1919
"ProductCatalog": {
2020
"commandName": "Project",
2121
"launchBrowser": true,
22-
"launchUrl": "http://localhost:5000/index.html",
22+
"launchUrl": "http://localhost:5000/ProductCatalog/Index",
2323
"environmentVariables": {
2424
"ASPNETCORE_ENVIRONMENT": "Development"
2525
}

0 commit comments

Comments
 (0)