Code First approach in MVC using Entity Framework - 2020:

Let us see, what is code first approach in MVC using Entity Framework.The Entity Framework has 3 types of approaches to connect to the database. The approaches are CodeFirst,ModelFirst and DatabaseFirst.The codefirst approach starts creating classes first and with that class name it creates tables in sqlserver database.You need to configure database name in web.config file.The same name will be created as new database in Sqlserver. For example, if you want to create user management system then you need to create 'User' class first and then 'UserRoles','Roles','UserLogins' and 'UserClaims' in your Model folder.

  • Create data model
  • Create the database context
  • Initialize DB with test data

Create data model
create entity class for login application.
public class User
{
public int Userid{get;set;}
public string UserName{get;set}
public string Password{get;set}
public string Email{get;set}
}
                    
Create the database context
Create DAL folder,Right click and create UserContext.cs

public class UserContext:DbContext
{
public UserContext():base('UserContext')
{
    Database.SetInitializer(new CustomDBInitializer())
}
public DbSet Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
}
}
                    
public class CustomDBInitializer:System.Data.Entity.DropCreateDatabaseIfModelChanges                            
{
protected override void Seed(UserContext context)(
{
var users=new List                                
{
new User { Username='Alex', Password='alex123', Email='alex@gmail.com' },
new User { Username='John', Password='john123', Email='johnraj@gmail.com' },
new User { Username='peter', Password='pet123', Email='peter@gmail.com' },
};
users.foreach(s=>context.users.Add(s));
context.SaveChanges();
}
}
                        
//Create connectionString for Database Context
  <connectionStrings>
  <add name='UserContext' connectionString='server=someservername;database=codefirstdb;uid=sa;password=sql123' providername= 'System.Data.SqlClient'>
  <connectionStrings>
                    
//Create User Controller
 public class UserController : Controller
 {
  private UserContext dbusers = new UserContext();
 public ActionResult Index()
 {
 return View(dbusers.Users.ToList());
 }
 }
         
Create Index.html
@model IEnumerable 
@foreach (var item in Model)
@Html.DisplayNameFor(m => m.Username)
                        

Now Run and see output
DEMO:CREATE ASP.NET MVC PROJECT USING CODE-FIRST APPROACH IN ENTITYFRAMEWORK PART 1