Tuesday, November 8, 2022

How to create database context class and adding tables to it? ASP.NET Core 6

CODE:

namespace projectnamespace;
public class Northwind : DbContext { 
var DataProvider="SQLite";
 
 protected override void OnConfiguring( DbContextOptionsBuilder     optionsBuilder) { 
 if (DatabaseProvider == "SQLite") { 
     string path = Path.Combine( Environment.CurrentDirectory, "Northwind.db"); 
 WriteLine($"Using {path} database file."); 

 optionsBuilder.UseSqlite($"Filename={path}"); 
 } else { 
     string connection = "Data Source=.;" + "Initial Catalog=Northwind;" + "Integrated Security=true;" + "MultipleActiveResultSets=true;";

     optionsBuilder.UseSqlServer(connection);
 } 
  public DbSet? Table1{ get; set; } 
  public DbSet? Table2{ get; set; }
}

DESCRIPTION:

Step to create asp.net core 6 database context class
  1. Create your DatabaseContext class
  2. Inherit it from DbContext
  3. Override OnConfiguring method
  4. Create connection string according to database provider.
  5. Add your connection string as a parameter inside optionsBuilder.UseSqlServer(connectionString) this is an example of SqlServer Databae provider.
  6. Add your tables as property of DbSet<T> type. these represents the tables.

No comments:

Post a Comment

methods available in Dapper

  Dapper is a micro ORM library for .NET and .NET Core applications that allows you to execute SQL queries and map the results to objects. D...