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.

%d bloggers like this: