Home  • Courses • Software Engineering

DbContext C# ASP.NET Core

Step 1 Create Db context class at Data folder in your project: You can do it either write code manually or with Scaffolding Command. Scaffold:
Scaffold-DbContext "Server=192.168.0.150;Database=ERP;User Id=sa;Password='password';Encrypt=False"  Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -ContextDir Data -Context RoleMasterContext  -t role_master -DataAnnotations
Manually:
using Microsoft.EntityFrameworkCore;

namespace ERP.Data
{
    public partial class Db : DbContext
    {
        //This is for without DI
        public Db()
        {
            // ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            //this.ChangeTracker.LazyLoadingEnabled = false;
        }

        //This contructor for DI
        public Db(DbContextOptions<Db> options) : base(options)
        {
            // ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
            // this.ChangeTracker.LazyLoadingEnabled = false;
        }


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {           
            optionsBuilder.UseSqlServer(ConnectionString.GetConnectionString(), providerOptions => { providerOptions.EnableRetryOnFailure(); });
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {           
           

            OnModelCreatingPartial(modelBuilder);

        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

        //System
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }      

    }
Step 2 Create User and Role models at Models folder if not present. User.cs
using System;
namespace ERP.Models;

class User{
    public int Id { get; set; }
    public string? Name { get; set; }
    public string? Password { get; set; }
    public int? RoleId { get; set; }
}
Role.cs
using System;
namespace ERP.Models;

class Role{
    public int Id { get; set; }
    public string? Name { get; set; }
}
Step 3 Open Program.cs file and write as follows:
using ERP.Data;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<Db>(options => options.UseSqlServer(ConnectionString.GetConnectionString()));
...

Comments 0


Copyright © 2025. Powered by Intellect Software Ltd