Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

StarWars

> 后端框架
Open source

GraphQL 'Star Wars' example using GraphQL for .NET, ASP.NET Core, Entity Framework Core

617 stars0 likes3 views
WebsiteGitHub

About

GraphQL 'Star Wars' example using GraphQL for .NET, ASP.NET Core, Entity Framework Core

GraphQL 'Star Wars' example using GraphQL for .NET, ASP.NET Core, Entity Framework Core

Examples

  • 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)

Roadmap

  • Basic
    • Simple tutorial (step/screenshot/code)
    • Detailed tutorial (steps explanation)
    • 3-Layers (Api, Core, Data) architecture
    • DDD (Domain Driven Design) hexagonal architecture
    • Dependency Inversion (deafult ASP.NET Core IoC container)
    • GraphQL controller
    • In Memory 'Droid' Repository
    • Entity Framework 'Droid' Repository
    • Automatic database creation
    • Seed database data
    • EF Migrations
    • GraphiQL
    • Unit Tests
    • Visual Studio 2017 RC upgrade
    • Integration Tests
    • Logs
    • Code Coverage
    • Continous Integration
  • Advanced
    • Full 'Star Wars' database (Episodes, Characters, Planets, Humans etc.)
    • Base/generic repository
    • Visual Studio 2017 RTM upgrade
    • Repositories
    • GraphQL queries
    • GraphQL mutations
    • Docker
  • PWA (Progressive Web App)
    • Identity microservice
    • Angular frontend
    • Apollo GraphQL Client for Angular
    • Service Worker
    • IndexedDB
    • ...

Tutorials

Basic

  • 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

json
"runtimes": {
   "win10-x64": { }
}
  • Install GraphQL NuGet package

  • Create 'StarWars.Core' project

  • Create 'Droid' model

csharp
namespace StarWars.Core.Models
{
    public class Droid
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
  • Create 'DroidType' model
csharp
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.");
        }
    }
}
  • Create 'StarWarsQuery' model
csharp
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" }
            );
        }
    }
}
  • Create 'GraphQLQuery' model
csharp
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; }
    }
}
  • Create 'GraphQLController'
…
  • Test using Postman

  • Create 'IDroidRepository' interface

csharp
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'

csharp
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));
        }
    }
}
  • Use 'IDroidRepository' in StarWarsQuery
csharp
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)
            );
        }
    }
}
  • Update creation of StarWarsQuery in GraphQLController
csharp
// ...
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

csharp
// ...
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddTransient();
    services.AddTransient();
}
// ...
  • Use constructor injection of StarWarsQuery in GraphQLController
csharp
// ...
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

csharp
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; }
    }
}
  • Update 'appsetting.json' with database connection
json
{
  "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;"
  }
}
  • Create EF droid repository
csharp
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);
        }
    }
}
  • Create seed data as an extension to StarWarsContext
csharp
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();
            }
        }
    }
}
  • Configure dependency injection and run data seed in Startup.cs
…
  • Run application and make sure database is created

  • Final test using Postman

Entity Framework Migrations

  • 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)

json
"tools": {
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final"
}
  • Add official workaround for problems with targeting class library (Modify your class library to be a startup application)
    • Add main entry point
    csharp
    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() { }
        }
    }
    • Add build option in project.json
    json
    "buildOptions": {
        "emitEntryPoint": true
    }
  • Run migrations command from the console
dotnet ef migrations add Inital -o .\EntityFramework\Migrations

GrahpiQL

  • Add NPM configuration file 'package.json' to StarWars.Api project

  • Add GraphiQL dependencies and webpack bundle task

json
{
  "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"
  }
}
  • Add webpack configuration 'webpack.config.js'
…
  • Install 'NPM Task Runner' extension

  • Configure 'After Build' step in 'Task Runner Explorer'

json
  "-vs-binding": { "AfterBuild": [ "start" ] }
  • Add 'Get' action to GraphQL controller and GraphiQL view (~/Views/GraphQL/index.cshtml)
csharp
// ...
public class GraphQLController : Controller
{
    // ...
    [HttpGet]
    public IActionResult Index()
    {
        return View();
    }    
// ...
}
xml

    
    
    GraphiQL
    

    

    
  • Add GraphiQL scripts and styles (app.js and app.css to ~/GraphiQL)

    • app.js
    javascript
    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'));
    • app.css
    css
    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'

    csharp
    // ...
    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

Unit Tests

  • 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

    • Set 'testRunner'
    • Reference 'StarWars.Data' project
    • Set 'runtimes'
json
{
  "version": "1.0.0-*",
  "testRunner": "xunit",
  "dependencies": {
    "dotnet-test

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C#asp-net-coredotnet-coreentity-framework-coregraphiql

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架