ASP Core C# Entity Framework Cheat Sheet

Step 1) Create Models – example

namespace Project.Models{
	public class Product{
		public int ID { get; set;}
		public string Name { get; set;}
		public string Description { get; set;}
		public decimal Price { get; set;}
		public string Category { get; set;}


Entity framework looks for properties with ID in it and makes that the primary key.
Step 2) Create Repository – example

using System.Collections.Generic;
using System.Linq;
namespace Project.Models {
 public class ProductRepository : IProductRepository {
 private ApplicationDbContext context;

 public ProductRepository(ApplicationDbContext context) {
 context = context;
 public IQueryable Products => context.Products;

Step 3) Create a Database Connection string and add it to appsettings

 "Data": {
 "Project": {
 "ConnectionString": "Server=(localdb)\\MSSQLLocalDB;Database=ProjectDB;Trusted_Conne

Step 4) Add DB Context as a service

Open Startup.cs
Look for the method

public void ConfigureServices(IServiceCollection services) 

Then add

services.AddDbContext(options =>

Step 5) Disable Scope Verification

Edit Program.cs

Look for

public static IWebHost BuildWebHost(string[] args) =>

Change to

public static IWebHost BuildWebHost(string[] args) =>
 .UseDefaultServiceProvider(options =>
 options.ValidateScopes = false)

Step 6) Database Migration

Open command prompt within the project folder (that contains your .sln)

doetnet ef migrations add Initial
dotnet ef database update

Leave a Reply

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