ASP.NET, ASP.NET Core, Entity Framework, Identity

ASP.NET Core MVC / Entity Framework / Repository Pattern

I’m going to be upgrading the same idea I’ve visited in the past but using ASP.NET Core this time. The plan is to structure a very simple architecture that allows us to build a web application above it. For this article I’ll be using a very simple Repository Pattern as a base for a ASP.NET Core Web Application.

The sample solution will have 3 projects: Domain, Data Access and Web Application layers. This time I will leave out the Business Logic layer to make this tutorial simpler and cleaner. You will be able to add your managers and services easily later.

The first step is to create a ASP.NET Core Application. For Authentication we will choose Single User. This will bake Identity into our project.

1.png
create the new Core Web App with Individual User Account

The following step is to create two .Net Core class library projects. One for our Domain objects and another one for the Data Access component. This part is tricky ! As for the time being, adding a new .Core class library will not allow you to select the framework from the UI. You will need to tweak your project.json to correctly use the Core Framework. In both cases, initially they should look like this:

2.png
Replace the default dependencies and frameworks to make it compatible with your Web App project

Domain Layer

As usual, we define a Domain layer. Here we define classes that will be used in the upper layers. You will need to add a reference to EntityFrameworkCore on this project (see the image above or use Nuget). Just make sure you use the same dependencies (versions) on your projects. On the sample code I have created the BaseEntity abstract class and two Domain Classes (Category and Product). I’m keeping this REALLY simple.

A substancia change here is how you define your DBContext:

3.PNG
Be prepared to deal with errors ! Add the constructor receiving the DBContextOptions. You will used it later.

Instead of having a constructor with the ConnectionString name we are using a special constructor that uses a DBContextOption object. This will allow you to configure this context later from the upper layers. The rest is pretty similar to the old fashion EF Context codding.

Data Access Layer

This layer is getting a lot thinner with Core. Since Dependency Injection is built in you can rely on it’s mechanisms to retain only one context through the execution of the request. Dependency Injection works by default at constructor level. Also, to make full use of DI we are going to be defining a lot of interfaces. This will allow us to write a very loose code. You can check the source code for how the repositories are built, I’m putting an example of a base repository here:


public abstract class BaseRepository<T> : IRepository<T> where T : BaseEntity
{
public DomainContext Context { get; set; }

public BaseRepository(DomainContext context)
{
Context = context;
}

public void Delete(T entity)
{
Context.Set<T>().Remove(entity);
Context.SaveChanges();
}

public T Get(Guid id)
{
return Context.Set<T>().Where(e => e.Id.Equals(id)).SingleOrDefault();
}

public IEnumerable<T> GetAll()
{
return Context.Set<T>().ToList();
}

public void Insert(T entity)
{
if (entity == null)
throw new ArgumentException("entity is null");

Context.Set<T>().Add(entity);
Context.SaveChanges();
}

public void Update(T entity)
{
if (entity == null)
throw new ArgumentException("entity is null");
Context.SaveChanges();
}

public void Dispose()
{
Context.Dispose();
GC.SuppressFinalize(this);
}
}

You can add your own repositories later following the sample code I’m providing. Just make your interfaces and make them use the correct base class.

Presentation Layer (Core MVC Project)

Here is where things get spiced up. If you are not familiar with ASP.NET CORE MVC you should read a bit. It’s not very complex and it will help you understand what’s going on.

Besides adding the references to the underlying Domain and Data Access libraries, you must configure your services (in other words, tell the dependency injection module how to deal with your repositories and interfaces). You also need to configure your DbContext (the identity context and our domain context).

All this is done editing the Startup.cs file. This is a replacement for the Global.asax and it’s where you are going to put all your services and middle-wares here. Routes are also defined here among other things. Let’s see how you tell the DI Engine to bind the interfaces and classes:

4.PNG

You will also need to configure your database connections here.

5.PNG

Remember our special constructor back on our Domain Layer ? Here is how it’s used. You are configuring your Context with a specific connection string (from the appsettings.json file) and you are letting it know you are using your top level project for migrations (in my case CoreFullStack). This last part is for convenience only: you can avoid it and install the EF migration tools on the Domain Layer. I just didn’t want to 🙂

You can now start adding your migrations with add-migration name -Context “name of your context” and update-database -Context “name of your context”.

If you reach this you are pretty much done ! You DI Engine knows how to instance your repositories and your context will be unique (bye bye unit of work !). Since DI is constructor based, if a Controller Requieres a Repository just add it to it’s constructor:

6.PNG

Notes about Identity

As before I have decided to keep the identity context and the domain context separated. In my personal opinion those two should not be tied together. This is a personal thing and I know it’s open to debate but mixing the context and layer level is not covered in this article (also, I have no idea how to do it yet !) This is why you have to use the -Context parameter on your migrations and updates. Just pay attention to those details !

Sample solution

As usual you can download the source code for this article from here:

https://github.com/aarcoraci/CORE1FULLSTACK

Advertisements

1 thought on “ASP.NET Core MVC / Entity Framework / Repository Pattern”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s