Entity Framework Core in Asp.Net Core 2.2

Seamless Integration

Entity Framework Core in Asp.Net Core 2.2

  1. Create a Database Context Class inherited from Microsoft.EntityFrameworkCore.DbContext and define DbSets with Database Models:

public class AssetTrackingDBContext: DbContext
    {
        public AssetTrackingDBContext(DbContextOptions<AssetTrackingDBContext> options) : base(options)
        {

        }

        public DbSet<Items> Items { get; set; }
        public DbSet<Units> Units { get; set; }
        public DbSet<Brands> Brands { get; set; }
        public DbSet<Categories> Categories { get; set; }
        public DbSet<SubCategories> SubCategories { get; set; }

    }

2. Create a ConnectionString in appsettings.json

 "ConnectionStrings": {
    "DefaultConnection": "Server=LAPTOP-LV007F3O\\MSSQLSERVER2016;Database=inventory;Trusted_Connection=True;MultipleActiveResultSets=true;"
  }

3. In the Startup class, add database context to the Service Collection

services.AddDbContext(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

4. Use the Database Context to query/execute SQL commands

No Comments

Add your comment

seventeen + 13 =