Skip to content

Commit d950226

Browse files
authored
Merge pull request #16 from f7q/ef-table-create
データベース自動生成
2 parents 2647577 + dc869e8 commit d950226

File tree

20 files changed

+784
-36
lines changed

20 files changed

+784
-36
lines changed

GroongaSample/NuGet.config

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<configuration>
3+
<packageSources>
4+
<clear />
5+
<add key="NuGet" value="https://api.nuget.org/v3/index.json" />
6+
</packageSources>
7+
</configuration>

GroongaSample/WebApiSample.sln

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 15
4+
VisualStudioVersion = 15.0.26430.15
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{E3F89342-C6EC-4C23-A6BB-05CF73ED91D1}"
7+
EndProject
8+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{29042E6E-467D-452D-AFD8-0CB8EE1A45B6}"
9+
EndProject
10+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WebApiSample", "src\WebApiSample\WebApiSample.csproj", "{4E33D213-0744-437E-AF0D-2AC91E05F5DB}"
11+
EndProject
12+
Global
13+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
14+
Debug|Any CPU = Debug|Any CPU
15+
Release|Any CPU = Release|Any CPU
16+
EndGlobalSection
17+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
18+
{4E33D213-0744-437E-AF0D-2AC91E05F5DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19+
{4E33D213-0744-437E-AF0D-2AC91E05F5DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
20+
{4E33D213-0744-437E-AF0D-2AC91E05F5DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
21+
{4E33D213-0744-437E-AF0D-2AC91E05F5DB}.Release|Any CPU.Build.0 = Release|Any CPU
22+
EndGlobalSection
23+
GlobalSection(SolutionProperties) = preSolution
24+
HideSolutionNode = FALSE
25+
EndGlobalSection
26+
GlobalSection(NestedProjects) = preSolution
27+
{4E33D213-0744-437E-AF0D-2AC91E05F5DB} = {E3F89342-C6EC-4C23-A6BB-05CF73ED91D1}
28+
EndGlobalSection
29+
EndGlobal

GroongaSample/global.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"projects": [ "src" ],
3+
"sdk": {
4+
"version": "1.0.0"
5+
}
6+
}
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
using System;
2+
using System.Linq;
3+
using Microsoft.AspNetCore.Mvc;
4+
using WebApiSample.Models;
5+
using Microsoft.Extensions.Logging;
6+
using Microsoft.EntityFrameworkCore;
7+
8+
namespace WebApiSample.Controllers
9+
{
10+
[Route("api/[controller]")]
11+
public class ValuesController : Controller
12+
{
13+
private SampleDbContext _dbContext { get; set; }
14+
private ILogger _logger { get; set; }
15+
16+
public ValuesController(SampleDbContext dbContext, ILogger<ValuesController> logger)
17+
{
18+
_dbContext = dbContext;
19+
_logger = logger;
20+
}
21+
// GET api/values
22+
[HttpGet]
23+
public IActionResult Get()
24+
{
25+
var result = _dbContext.Values.OrderBy(i => i.Name);
26+
if (result != null)
27+
{
28+
return Ok(result);
29+
}
30+
return NotFound();
31+
}
32+
33+
// GET api/values/5
34+
[HttpGet("{name}")]
35+
public IActionResult Get(string name)
36+
{
37+
var sql = _dbContext.Values.Where(i => i.Name == name).ToSql();
38+
_logger.LogInformation("before sql{@}", sql);
39+
sql = sql.Replace("=", "&@~"); // AND ORは大文字
40+
_logger.LogInformation("after sql{@}", sql);
41+
var result = _dbContext.Values.FromSql(sql).ToList();
42+
if (result != null)
43+
{
44+
return Ok(result);
45+
}
46+
return NotFound();
47+
}
48+
49+
// POST api/values
50+
[HttpPost]
51+
public IActionResult Post([FromBody]Value value)
52+
{
53+
try
54+
{
55+
_dbContext.Values.Add(value);
56+
_dbContext.SaveChanges();
57+
return Ok();
58+
}
59+
catch (Exception ex)
60+
{
61+
_logger.LogInformation(ex.ToString());
62+
return new NotFoundResult();
63+
}
64+
}
65+
66+
// PUT api/values/5
67+
[HttpPut("{id}")]
68+
public IActionResult Put(int id, [FromBody]Value value)
69+
{
70+
try
71+
{
72+
var result = _dbContext.Values.Where(i => i.Id == id).First();
73+
if(result != null) {
74+
_dbContext.Values.Update(value);
75+
_dbContext.SaveChanges();
76+
}
77+
else
78+
{
79+
_dbContext.Values.Add(value);
80+
_dbContext.SaveChanges();
81+
}
82+
return Ok();
83+
}
84+
catch (Exception ex)
85+
{
86+
_logger.LogInformation(ex.ToString());
87+
return new NotFoundResult();
88+
}
89+
}
90+
91+
// DELETE api/values/5
92+
[HttpDelete("{id}")]
93+
public IActionResult Delete(int id)
94+
{
95+
try {
96+
var value = _dbContext.Values.Where(i => i.Id == id).First();
97+
_dbContext.Values.Remove(value);
98+
_dbContext.SaveChanges();
99+
return Ok();
100+
}
101+
catch (Exception ex)
102+
{
103+
_logger.LogInformation(ex.ToString());
104+
return new NotFoundResult();
105+
106+
}
107+
}
108+
}
109+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
using Microsoft.EntityFrameworkCore.Internal;
6+
using Microsoft.EntityFrameworkCore.Query;
7+
using Microsoft.EntityFrameworkCore.Query.Internal;
8+
using Microsoft.EntityFrameworkCore.Storage;
9+
using System.Reflection;
10+
using Remotion.Linq.Parsing.Structure;
11+
12+
namespace WebApiSample
13+
{
14+
public static class IQueryableExtensions
15+
{
16+
private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo();
17+
18+
private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler");
19+
20+
private static readonly PropertyInfo NodeTypeProviderField = QueryCompilerTypeInfo.DeclaredProperties.Single(x => x.Name == "NodeTypeProvider");
21+
22+
private static readonly MethodInfo CreateQueryParserMethod = QueryCompilerTypeInfo.DeclaredMethods.First(x => x.Name == "CreateQueryParser");
23+
24+
private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database");
25+
26+
private static readonly FieldInfo QueryCompilationContextFactoryField = typeof(Database).GetTypeInfo().DeclaredFields.Single(x => x.Name == "_queryCompilationContextFactory");
27+
28+
public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
29+
{
30+
if (!(query is EntityQueryable<TEntity>) && !(query is InternalDbSet<TEntity>))
31+
{
32+
throw new ArgumentException("Invalid query");
33+
}
34+
35+
var queryCompiler = (IQueryCompiler)QueryCompilerField.GetValue(query.Provider);
36+
var nodeTypeProvider = (INodeTypeProvider)NodeTypeProviderField.GetValue(queryCompiler);
37+
var parser = (IQueryParser)CreateQueryParserMethod.Invoke(queryCompiler, new object[] { nodeTypeProvider });
38+
var queryModel = parser.GetParsedQuery(query.Expression);
39+
var database = DataBaseField.GetValue(queryCompiler);
40+
var queryCompilationContextFactory = (IQueryCompilationContextFactory)QueryCompilationContextFactoryField.GetValue(database);
41+
var queryCompilationContext = queryCompilationContextFactory.Create(false);
42+
var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
43+
modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
44+
var sql = modelVisitor.Queries.First().ToString();
45+
46+
return sql;
47+
}
48+
}
49+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.IO;
3+
using System.Collections.Generic;
4+
using System.Linq;
5+
using System.Threading.Tasks;
6+
using Microsoft.Extensions.Configuration;
7+
using Microsoft.EntityFrameworkCore;
8+
9+
namespace WebApiSample.Models
10+
{
11+
public class SampleDbContext : DbContext
12+
{
13+
public SampleDbContext(DbContextOptions<SampleDbContext> options) :base(options)
14+
{
15+
16+
}
17+
18+
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
19+
{
20+
if (!optionsBuilder.IsConfigured)
21+
{
22+
var config = new ConfigurationBuilder()
23+
.SetBasePath(Directory.GetCurrentDirectory())
24+
.AddJsonFile("appsettings.json")
25+
.Build();
26+
27+
var dbkind = config["Data:DefaultConnection:ConnectionDBString"];
28+
if(dbkind.Equals("sqlite"))
29+
{
30+
optionsBuilder.UseSqlite(config["Data:DefaultConnection:ConnectionString"]);
31+
}
32+
if (dbkind.Equals("sqlserver"))
33+
{
34+
optionsBuilder.UseSqlServer(config["Data:DefaultConnection:ConnectionString"]);
35+
}
36+
if (dbkind.Equals("postgresql"))
37+
{
38+
optionsBuilder.UseNpgsql(config["Data:DefaultConnection:ConnectionString"]);
39+
}
40+
if (dbkind.Equals("inmemory"))
41+
{
42+
optionsBuilder.UseInMemoryDatabase();
43+
}
44+
}
45+
46+
//base.OnConfiguring(optionsBuilder);
47+
}
48+
49+
public DbSet<Value> Values { get; set; }
50+
51+
protected override void OnModelCreating(ModelBuilder builder)
52+
{
53+
builder.Entity<Value>().HasKey(m => m.Id);
54+
base.OnModelCreating(builder);
55+
}
56+
}
57+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Threading.Tasks;
5+
6+
namespace WebApiSample.Models
7+
{
8+
public class Value
9+
{
10+
public int Id { get; set; }
11+
public string Name { get; set; }
12+
}
13+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Linq;
5+
using System.Threading.Tasks;
6+
using Microsoft.AspNetCore.Hosting;
7+
using Microsoft.AspNetCore.Builder;
8+
9+
namespace WebApiSample
10+
{
11+
public class Program
12+
{
13+
public static void Main(string[] args)
14+
{
15+
var host = new WebHostBuilder()
16+
.UseKestrel()
17+
.UseContentRoot(Directory.GetCurrentDirectory())
18+
.UseIISIntegration()
19+
.UseStartup<Startup>()
20+
.Build();
21+
22+
host.Run();
23+
}
24+
}
25+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"iisSettings": {
3+
"windowsAuthentication": false,
4+
"anonymousAuthentication": true,
5+
"iisExpress": {
6+
"applicationUrl": "http://localhost:56006/",
7+
"sslPort": 0
8+
}
9+
},
10+
"profiles": {
11+
"IIS Express": {
12+
"commandName": "IISExpress",
13+
"launchBrowser": true,
14+
"launchUrl": "api/values",
15+
"environmentVariables": {
16+
"ASPNETCORE_ENVIRONMENT": "Development"
17+
}
18+
},
19+
"WebApiSample": {
20+
"commandName": "Project",
21+
"launchBrowser": true,
22+
"launchUrl": "http://localhost:5000/api/values",
23+
"environmentVariables": {
24+
"ASPNETCORE_ENVIRONMENT": "Development"
25+
}
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)