Skip to content

Instantly share code, notes, and snippets.

@abhishekluv
Created February 10, 2020 11:54
Show Gist options
  • Save abhishekluv/f1bba1cc37adf69c42da388a3dfdda3a to your computer and use it in GitHub Desktop.
Save abhishekluv/f1bba1cc37adf69c42da388a3dfdda3a to your computer and use it in GitHub Desktop.
ASP.NET Source Code Demo 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity; // DbContext
using MVCDay8.Initializers;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCDay8.Models
{
public class DatabaseContext : DbContext
{
public DatabaseContext() : base("MVCDay8")
{
//0. Default Initializer
//Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
//1. DropCreateDatabaseAlways
Database.SetInitializer<DatabaseContext>(new DropCreateDatabaseAlways<DatabaseContext>());
//2. DropCreateDatabaseIfModelChanges
//Database.SetInitializer<DatabaseContext>(new DropCreateDatabaseIfModelChanges<DatabaseContext>());
//3. Custom Db Initializer
//Database.SetInitializer<DatabaseContext>(new CustomDbInitializer());
//4. Null Initializer
//turning off database initializer feature for safety reasons
//Database.SetInitializer<DatabaseContext>(null);
}
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Project> Projects { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//0. turn off the pluralization
//PluralizingTableNameConvention
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//1. setting EmpId as primary key
modelBuilder.Entity<Employee>().HasKey(x => x.EmpId);
modelBuilder.Entity<Department>().HasKey(x => x.DepId);
//2. setting a custom table name
modelBuilder.Entity<Employee>().ToTable("Employee_tbl");
modelBuilder.Entity<Department>().ToTable("Departments");
//3. changing column name, type, character restriction, not null
modelBuilder.Entity<Employee>()
.Property(x => x.LastName)
.HasColumnName("EmployeeLN")
.HasColumnType("varchar")
.HasMaxLength(50)
.IsRequired();
//4. configuring many-to-many relationship
modelBuilder.Entity<Employee>()
.HasMany(x => x.Projects)
.WithMany(x => x.Employees)
.Map(x =>
{
x.MapLeftKey("EmpId");
x.MapRightKey("ProjectId");
x.ToTable("EmpProjects");
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment