使用 GraphQL for .NET、ASP.NET Core 和 Entity Framework Core 的 GraphQL '星球大战'示例
使用 GraphQL for .NET、ASP.NET Core 和 Entity Framework Core 的 GraphQL '星球大战'示例
Basic - simple 'Hello GraphQL!' example based on console version from GraphQL for .NET on GitHub, but using ASP.NET Core, Entity Framework Core and some best practices, patterns and principles.
Advanced - GraphQL queries and mutations with full 'Star Wars' database (see GraphQL Specification by Facebook and GraphQL.js - reference implementation)
Create 'StarWars' empty solution
Add 'ASP.NET Core Web Application (.NET Core)' project named 'StarWars.Api'
Select Web API template
Update all NuGet packages
Update project.json with correct runtime
"runtimes": {
"win10-x64": { }
}Install GraphQL NuGet package
Create 'StarWars.Core' project
Create 'Droid' model
namespace StarWars.Core.Models
{
public class Droid
{
public int Id { get; set; }
public string Name { get; set; }
}
}using GraphQL.Types;
using StarWars.Core.Models;
namespace StarWars.Api.Models
{
public class DroidType : ObjectGraphType
{
public DroidType()
{
Field(x => x.Id).Description("The Id of the Droid.");
Field(x => x.Name, nullable: true).Description("The name of the Droid.");
}
}
}using GraphQL.Types;
using StarWars.Core.Models;
namespace StarWars.Api.Models
{
public class StarWarsQuery : ObjectGraphType
{
public StarWarsQuery()
{
Field(
"hero",
resolve: context => new Droid { Id = 1, Name = "R2-D2" }
);
}
}
}namespace StarWars.Api.Models
{
public class GraphQLQuery
{
public string OperationName { get; set; }
public string NamedQuery { get; set; }
public string Query { get; set; }
public string Variables { get; set; }
}
}…Test using Postman
Create 'IDroidRepository' interface
using StarWars.Core.Models;
using System.Threading.Tasks;
namespace StarWars.Core.Data
{
public interface IDroidRepository
{
Task Get(int id);
}
}Create 'StarWars.Data' project
Create in memory 'DroidRepository'
using StarWars.Core.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
using StarWars.Core.Models;
using System.Linq;
namespace StarWars.Data.InMemory
{
public class DroidRepository : IDroidRepository
{
private List _droids = new List {
new Droid { Id = 1, Name = "R2-D2" }
};
public Task Get(int id)
{
return Task.FromResult(_droids.FirstOrDefault(droid => droid.Id == id));
}
}
}using GraphQL.Types;
using StarWars.Core.Data;
namespace StarWars.Api.Models
{
public class StarWarsQuery : ObjectGraphType
{
private IDroidRepository _droidRepository { get; set; }
public StarWarsQuery(IDroidRepository _droidRepository)
{
Field(
"hero",
resolve: context => _droidRepository.Get(1)
);
}
}
}// ...
public async Task Post([FromBody] GraphQLQuery query)
{
var schema = new Schema { Query = new StarWarsQuery(new DroidRepository()) };
// ...Test using Postman
Configure dependency injection in Startup.cs
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient();
services.AddTransient();
}
// ...// ...
public class GraphQLController : Controller
{
private StarWarsQuery _starWarsQuery { get; set; }
public GraphQLController(StarWarsQuery starWarsQuery)
{
_starWarsQuery = starWarsQuery;
}
[HttpPost]
public async Task Post([FromBody] GraphQLQuery query)
{
var schema = new Schema { Query = _starWarsQuery };
// ...Add Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer Nuget packages to StarWars.Data project
Create StarWarsContext
using Microsoft.EntityFrameworkCore;
using StarWars.Core.Models;
namespace StarWars.Data.EntityFramework
{
public class StarWarsContext : DbContext
{
public StarWarsContext(DbContextOptions options)
: base(options)
{
Database.EnsureCreated();
}
public DbSet Droids { get; set; }
}
}{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"StarWarsDatabaseConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=StarWars;Integrated Security=SSPI;integrated security=true;MultipleActiveResultSets=True;"
}
}using StarWars.Core.Data;
using System.Threading.Tasks;
using StarWars.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace StarWars.Data.EntityFramework.Repositories
{
public class DroidRepository : IDroidRepository
{
private StarWarsContext _db { get; set; }
public DroidRepository(StarWarsContext db)
{
_db = db;
}
public Task Get(int id)
{
return _db.Droids.FirstOrDefaultAsync(droid => droid.Id == id);
}
}
}using StarWars.Core.Models;
using System.Linq;
namespace StarWars.Data.EntityFramework.Seed
{
public static class StarWarsSeedData
{
public static void EnsureSeedData(this StarWarsContext db)
{
if (!db.Droids.Any())
{
var droid = new Droid
{
Name = "R2-D2"
};
db.Droids.Add(droid);
db.SaveChanges();
}
}
}
}…Run application and make sure database is created
Final test using Postman
Add 'Microsoft.EntityFrameworkCore.Design' NuGet package to 'StarWars.Data' project
Add 'Microsoft.EntityFrameworkCore.Tools.DotNet' NuGet package to 'StarWars.Data' project
Add tools section in project.json (StarWars.Data)
"tools": {
"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final"
}namespace StarWars.Data.EntityFramework.Workaround
{
// WORKAROUND: https://docs.efproject.net/en/latest/miscellaneous/cli/dotnet.html#targeting-class-library-projects-is-not-supported
public static class Program
{
public static void Main() { }
}
}"buildOptions": {
"emitEntryPoint": true
}dotnet ef migrations add Inital -o .\EntityFramework\MigrationsAdd NPM configuration file 'package.json' to StarWars.Api project
Add GraphiQL dependencies and webpack bundle task
{
"version": "1.0.0",
"name": "starwars-graphiql",
"private": true,
"scripts": {
"start": "webpack --progress"
},
"dependencies": {
"graphiql": "^0.7.8",
"graphql": "^0.7.0",
"isomorphic-fetch": "^2.1.1",
"react": "^15.3.1",
"react-dom": "^15.3.1"
},
"devDependencies": {
"babel": "^5.6.14",
"babel-loader": "^5.3.2",
"css-loader": "^0.24.0",
"extract-text-webpack-plugin": "^1.0.1",
"postcss-loader": "^0.10.1",
"style-loader": "^0.13.1",
"webpack": "^1.13.0"
}
}…Install 'NPM Task Runner' extension
Configure 'After Build' step in 'Task Runner Explorer'
"-vs-binding": { "AfterBuild": [ "start" ] }// ...
public class GraphQLController : Controller
{
// ...
[HttpGet]
public IActionResult Index()
{
return View();
}
// ...
}
GraphiQL
Add GraphiQL scripts and styles (app.js and app.css to ~/GraphiQL)
import React from 'react';
import ReactDOM from 'react-dom';
import GraphiQL from 'graphiql';
import fetch from 'isomorphic-fetch';
import 'graphiql/graphiql.css';
import './app.css';
function graphQLFetcher(graphQLParams) {
return fetch(window.location.origin + '/graphql', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(graphQLParams)
}).then(response => response.json());
}
ReactDOM.render(, document.getElementById('app'));html, body {
height: 100%;
margin: 0;
overflow: hidden;
width: 100%;
}
#app {
height: 100vh;
}Add static files support
Add 'Microsoft.AspNetCore.StaticFiles' NuGet
Update configuration in 'Startup.cs'
// ...
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, StarWarsContext db)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseStaticFiles();
app.UseMvc();
db.EnsureSeedData();
}
// ...Build project and check if bundles were created by webpack under ~/wwwroot
Run project and enjoy GraphiQL
Create 'Class Library (.NET Core)' type 'StarWars.Tests.Unit' project
Install 'xunit' NuGet package in StarWars.Tests.Unit project
Install 'dotnet-test-xunit' NuGet package in StarWars.Tests.Unit project
Make changes to project.json
{
"version": "1.0.0-*",
"testRunner": "xunit",
"dependencies": {
"dotnet-test暂无开放 Issues,或尚未同步最近议题。