Introduction to ASP.NET Core part 23: the EntityFramework repository

Introduction

In the previous post we started looking into EntityFramework Core. We saw how to install and wire up EF Core using NuGet and Startup.cs. We also discussed the basics of creating a DB context class with a single DB set of the Book domain. The Update-Database command in the package manager detects our DB context class in the project and creates a data migration file. The console also enabled us to create the database and the Books table table using code-first and EF data migrations with the help of the generated migration class. That’s where we can declare in code what type of objects we want to create in the database: tables, indexes, primary keys etc.

The next step is to actually use this database in our demo book store project. We’ll do that in this post.

The book store repository

Recall that we have the following repository interface for the Book domain:

public interface IBookRepository
{
	IEnumerable<Book> GetAll();
	Book GetBy(int id);
	void AddNew(Book book);
}

We want to implement this interface so that we target the database we created in the previous post.

Before we do that let’s insert another interface with a single method in the Repositories folder:

namespace DotNetCoreBookstore.Repositories
{
    public interface ICommittableRepository
    {
		void CommitChanges();
    }
}

We’ll soon see the usage of this interface and this single function. In short the CommitChanges will need to be called after the data store related modifications have been called. This is in line with how the EF DB context works with the SaveChanges/SubmitChanges function after the various insertion and update related operations were executed. We let IBookRepository implement the interface:

public interface IBookRepository : ICommittableRepository
{
	IEnumerable<Book> GetAll();
	Book GetBy(int id);
	void AddNew(Book book);
}

…which will cause a compilation error since the DebugBookRepository class does not implement this last function. DebugBookRepository has no use for a separate commit function so we’ll leave it empty:

public void CommitChanges()
{
	
}

We can now add a new implementation of IBookRepository to the Repositories folder:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCoreBookstore.Domains;

namespace DotNetCoreBookstore.Repositories
{
	public class BookStoreRepository : IBookRepository
	{
		private readonly BookStoreDbContext _bookStoreDbContext;

		public BookStoreRepository(BookStoreDbContext bookStoreDbContext)
		{
			if (bookStoreDbContext == null) throw new ArgumentNullException("Book store DB context");
			_bookStoreDbContext = bookStoreDbContext;
		}

		public void AddNew(Book book)
		{
			_bookStoreDbContext.Books.Add(book);
		}

		public void CommitChanges()
		{
			_bookStoreDbContext.SaveChanges();
		}

		public IEnumerable<Book> GetAll()
		{
			return _bookStoreDbContext.Books;
		}

		public Book GetBy(int id)
		{
			return (from b in _bookStoreDbContext.Books where b.Id == id select b).FirstOrDefault();
		}
	}
}

We use the BookStoreDbContext object to communicate with the data store. This code is the same as in traditional LINQ to Entities with EF 6. We use the context to add a new book, save the changes, get all books and get a book by its ID. Recall that we registered the DB context in Startup.cs:

services.AddDbContext<BookStoreDbContext>(dbContextOptionsBuilder => dbContextOptionsBuilder.UseSqlServer(Configuration.GetConnectionString("BookStore")));

This will take care of constructing a BookStoreRepository object which requires a BookStoreDbContext dependency through its constructor.

Next we need to register in Startup.cs that we want to use the BookStoreDbContext implementation of IBookRepository instead of DebugBookRepository:

services.AddScoped<IBookRepository, BookStoreRepository>();

We also need to extend the AddNew function of DebugBookService so that we commit the changes:

public void AddNew(Book book)
{
	try
	{
		_bookRepository.AddNew(book);
		_bookRepository.CommitChanges();			
	}
	catch
	{
		throw;
	}
}

Lastly let’s fill up the Books table via the SQL Server Object Explorer. Open the (localdb) node and then expand Databases, then BookStore and then the Tables folder. Right-click the Books table and select the View Data menu option. You can insert records manually in this screen:

Insert starting records in books table for .NET Core demo application

Run the application and it should work like before. Test adding a new book and it should be saved in the database and then listed on the /books page.

We’ll continue in the next post.

View the list of MVC and Web API related posts here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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 )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: