Database-First Entity Framework in .NET Core

.NET Core and Entity Framework make connecting to an existing database really easy. This post will demonstrate how to generate models for an existing database using .NET Core Entity Framework. Note that you must have the .NET Core SDK installed.

First, let’s create a new console application. Open a new terminal and run the following commands:

/> dotnet new console -o MyConsoleApp
/> cd MyConsoleApp

If your app is using ASP.NET Core 2.1+, you’ll get all the Entity Framework packages you need. However, our console app is using .NET Core (not ASP.NET Core), so we need to install a couple more packages. Run the following commands:

/> dotnet add package Microsoft.EntityFrameworkCore.Design
/> dotnet add package Microsoft.EntityFrameworkCore.SqlServer

Now we’re ready to create our models. Again, we’ll do this by running a command in the terminal. Run the following command to generate models for all tables in your database along with a DbContext.

/> dotnet ef dbcontext scaffold "<connection string>" Microsoft.EntityFrameworkCore.SqlServer -o Models

Need help obtaining the connection string? If you’re using SQL Azure, you can browse to the database in the Azure Portal, and click the Connection Strings link.

With your DbContext and models created, you should now be able to write code to access tables. Add the following lines to your console app’s Program.cs:

using System;
using System.Linq;
using MyConsoleApp.Models;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            using (var context = new YourDatabaseNameContext())
            {
                var foo = context.SomeTable.First();
            }
        }
    }
}
Advertisement

One-Step React App with .NET Core Web API Backend

Last week, I wrote a short article demonstrating how to create a React app using Create React App and hook it up to a .NET Core Web API created by dotnet new webapi. Dotnet new also has a react template, though, which allows you to create a new React app with .NET Core web API backend in a single step.

/> dotnet new react -o my-app
/> cd my-app
/> dotnet run

Note! The front-end client and backend API still run as separate servers, so you must still specify the proxy in the React app. Perform the following steps to do this:

  1. Open package.json in the /ClientApp folder
  2. Add "proxy":"https://localhost:5001"
  3. Save & restart your app
  4. Verify API communication by viewing the Fetch Data page

There are some differences between the two approaches. Create React App creates a better-looking but more-barebones site. Dotnet new starts you with a more complex React site with basic navigation and multiple pages.

Create a React App with .NET Core Web API Backend

React and .NET Core Web API both provide super-simple tools that let you magically spit out a fully-functional application by executing a single command. Making the two work together is pretty easy, but there are a couple not-so-obvious steps that you need to take that aren’t explained in the 1-step, just-run-this-command getting-started guides you’ll come across. This article will walk you through the steps of creating new React and .NET Core Web API applications, then modifying the React app to make an API request and display the result.

Create the React App

The easiest way to create a new React app from scratch is with Create React App. Run the npx command, and you’re done!

/> npx create-react-app my-app
/> cd my-app
/> npm start

Create the Web API

Creating a .NET Core ASP.Net web API is just as easy. Run the dotnet command, and you’ve got your API.

/> dotnet new webapi -o my-api
/> cd my-api
/> dotnet run

Specify Proxy

React app: check. .NET Core API: check. Now let’s hook ’em up. The out-of-the-box API comes with a /api/values endpoint, so let’s use that to retrieve and display values on our home page.

By default, the React app is going to run on http://localhost:3000 and the API on https://localhost:5001. Since our app and API are running on different servers, we must specify a proxy. Open package.json in the React app, and add the line shown below. Note that if your app is running, you’ll need to restart it for the setting to take effect.

{
  "name": "my-app",
  ...
  "proxy": "https://localhost:5001"
}

Make Request, Display Result

Now we’re ready to add the API request. Open your React app’s App.js file, found in the /src folder. Add a constructor that will execute the request, and modify render() to display the result.

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { values: [] };

    fetch('/api/values')
      .then(response => response.json())
      .then(data => {
        this.setState({ values: data });
      });
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          Can I haz values? 
          <ul>
            {this.state.values.map((value, index) => <li key={index}>{value}</li>)}
          </ul>
        </header>
      </div>
    );
  }
}

All that’s left now is to run the projects. Start the API first, followed by the React app. The result should be something like this!

%d bloggers like this: