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
ction=True;MultipleActiveResultSets=true"
 }
 }
}

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 =>
 options.UseSqlServer(
 Configuration["Data:Project:ConnectionString"]));
 services.AddTransient();

Step 5) Disable Scope Verification

Edit Program.cs

Look for

public static IWebHost BuildWebHost(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .UseStartup()
 .Build();
 }

Change to

public static IWebHost BuildWebHost(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .UseStartup()
 .UseDefaultServiceProvider(options =>
 options.ValidateScopes = false)
 .Build();
 }

Step 6) Database Migration

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

doetnet ef migrations add Initial
dotnet ef database update

Leave a Reply

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