Using Entity Framework Core 2.0 (EFC2)

About EFC2

The Entity Framework is a set of technologies that support the development of data-oriented applications to work with relational data. It is is an ORM.

The Entity Framework provides services like tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals. It enables developers to work with data in the form of domain-specific objects and properties.

Entity Framework (EF) Core is a lightweight, extensible, and cross-platform version of the Entity Framework data access technology.Entity framework supports various database provider including Microsoft SQL Server, SQLite, PostgreSQL, MySQL. We can use EFC2 in Full .Net Application, UWP, and .Net Core.

Through this series we will learn how to handle CRUD operations, Code First & Data First Approaches, Migration & Seeding, and Advance Data, Entity, Model concepts.

Along with this we will also see how to send request from PCM & dotnet ef commands.

Videos: If you are interested to learn Entity Framework Core 2.0 (EFC2) using ASP.Net Core then you can visit my video series on Udemy (10$).

EF Core 1.0 was released alongside ASP.NET Core 1.0 on June 27, 2016 And at time of recording this series EF core 2.0 is in development branch, may at that time you watch it was public released. Entity framework supports various database provider including

  • Microsoft SQL Server
  • Microsoft SQL Server Compact Edition
  • SQLite
  • PostgreSQL
  • MySQL
  • IBM’s DB2
  • Devart which provide support to various database engine such as oracle.
  • And InMemory for testing

Install EFC2

First of all you need to create a new project of .Net Core 2.0, here I am going to create ASP.Net core 2.0 web app using visual studio. But you can use appropriate IDE.

After creating Project, we need to install some packages for Entity Framework Core. For this, you can use NuGet package manager or use package manager console.

At time of writing this blog EFC2.0 is under pre-release so here i need to use -Pre operator.

PM > Install-Package Microsoft.EntityFrameworkCore -Version 2.0.0-preview1-final -Pre 
PM > Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.0-preview1-final -Pre
PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 2.0.0-preview1-final -Pre 
PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design -Version 2.0.0-preview1-final -Pre

Entity Framework Packages

Code First Approach

In Code First Approach we need to design Model classes and DBContext. Here I have created Model classes for Author and Book, so it will create those 2 tables based on that fields.

namespace CodeFirst.Models
{
	public class Author
	{
		public int AuthorId { get; set; }
		public string Name { get; set; }
		public string MailId { get; set; }

		public ICollection<Book> Books { get; set; }
	}

	public class Book
	{
		public int Id { get; set; }
		public string Title { get; set; }
		public string Description { get; set; }
		public int AuthorId { get; set; }
		public double Price { get; set; }

		public Author Author { get; set; }
	}
}

After creating Models for each table we need to create the Database Context class. It must extend DbContext. click on plus sign near intents. Create the constructor for that and pass DbContextOptions to its base class. For each of table, we need to create the property of DbSet type just as below.

namespace CodeFirst.Data
{
	public class LibraryContext: DbContext
	{
		public LibraryContext(DbContextOptions<LibraryContext> options)
			: base (options)
		{
		}

		public DbSet<Author> Author { get; set; }
		public DbSet<Book> Book { get; set; }
	}
}

After this, we need to put dependency injection for Entity Framework. For this open Startup.cs and write AddDbContext() statement in ConfigureServices() method.

public void ConfigureServices(IServiceCollection services)
{
	services.AddDbContext<LibraryContext>(option =>
		option.UseSqlServer(Configuration.GetConnectionString("LibraryConnectionString")));
	services.AddMvc();
}

If you have noticed in dependency injection we have obtained connection string for a database from configurations. So we need to add it in appsettings.json.

"ConnectionStrings": {
	"LibraryConnectionString": "Data Source=MNILAY-ENVY\\SQLEXPRESS;..."
},

Videos: If you are interested to learn Entity Framework Core 2.0 (EFC2) using ASP.Net Core then you can visit my video series on Udemy (10$).

After this, we need to create a new controller. In the controller, we will get LibraryContext via Dependency Injection. When the user opens Index action I am checking that database is created as per our Model classes. For this, we need to use EnsureCreated() of Database.

public class HomeController : Controller
{
	private LibraryContext _context;

	public HomeController(LibraryContext context)
	{
		_context = context;
	}

	public string Index()
	{
		_context.Database.EnsureCreated();
		return "DB Created";
	}
}

After this, we need to create actions for performing CRUD operations on our Book table. Here I have not used any Advance MVC concepts & Business layer, just write everything in Controller. But you can make changes as per your requirements.

public string CreateBook(Book b)
{
	try
	{
		if (b.Title != null && b.Price != 0 && b.Description != null && b.AuthorId != 0)
		{
			_context.Book.Add(b);
			_context.SaveChanges();
			return "Book details added successfully.";
		}
		else
			return "Missing some Properties!";
	}
	catch(Exception ex)
	{
		return ex.Message;
	}
}

public string ReadBook()
{
	var books = _context.Book.Include("Author").AsNoTracking();
	StringBuilder sb = new StringBuilder();
	if (books == null)
		return "Not found any books!";
	else
	{
		foreach (var book in books)
		{
			sb.Append($"Book Id: {book.Id}\r\n");
			sb.Append($"Title: {book.Title}\r\n");
			sb.Append($"Book Description: {book.Description}\r\n");
			sb.Append($"Book Price: {book.Price}\r\n");
			sb.Append($"Author Id: {book.Author.AuthorId}\r\n");
			sb.Append($"Author Name: {book.Author.Name}\r\n");
			sb.Append($"Author Mail Id: {book.Author.MailId}\r\n");
			sb.Append("###############################################\r\n");
		}
		return sb.ToString();
	}
}

public string BookDetails(int? bookId)
{
	if (bookId == null)
		return "Enter book id!";

	var result = _context.Book.Include("Author").AsNoTracking()
		.SingleOrDefaultAsync(b => b.Id == bookId);
	StringBuilder sb = new StringBuilder();
	var book = result.Result;

	if (book == null)
		return "Not found book with given id!";
	else
	{
		sb.Append($"Book Id: {book.Id}\r\n");
		sb.Append($"Title: {book.Title}\r\n");
		sb.Append($"Book Description: {book.Description}\r\n");
		sb.Append($"Book Price: {book.Price}\r\n");
		sb.Append($"Author Id: {book.Author.AuthorId}\r\n");
		sb.Append($"Author Name: {book.Author.Name}\r\n");
		sb.Append($"Author Mail Id: {book.Author.MailId}\r\n");
		return sb.ToString();
	}
}

public string UpdateBook(int bookId, Book newBook)
{
	try
	{
		if (bookId != newBook.Id)
			return "Invalid data!";
		else
		{
			if (newBook.Title != null && newBook.Price != 0 && newBook.Description != null && newBook.AuthorId != 0)
			{
				//_context.Update(newBook);
				//_context.SaveChanges();
				//return "Book details updated successfully.";

				var dbBook = _context.Book.SingleOrDefaultAsync(book => book.Id == bookId);
				dbBook.Result.Title = newBook.Title;
				dbBook.Result.Price = newBook.Price;
				dbBook.Result.Description = newBook.Description;
				dbBook.Result.AuthorId = newBook.AuthorId;
				_context.SaveChanges();
				return "Book details updated successfully.";
			}
			else
				return "Missing some Properties!";
		}
	}
	catch (Exception ex)
	{
		return ex.Message;
	}
}

public string DeleteBook(int bookId)
{
	try
	{
		if (bookId == 0)
			return "Enter Book Id!";
		else
		{
			var result = _context.Book.SingleOrDefaultAsync(b => b.Id == bookId);
			var book = result.Result;
			if (book == null)
				return "Not found book details with given Id";
			else
			{
				_context.Book.Remove(book);
				_context.SaveChanges();
				return "Book details deleted successfully.";
			}
		}
	}
	catch (Exception ex)
	{
		return ex.Message;
	}
}

Videos: If you are interested to learn Entity Framework Core 2.0 (EFC2) using ASP.Net Core then you can visit my video series on Udemy (10$).

Leave a Reply

Your email address will not be published. Required fields are marked *