DbContext: Simplified
alternative to Object Context and is the primary object for interacting with a
database using a specific model.
DbSet : Simplified alternative to Object Set and is used to perform CRUD operations against a specific type from the model.
DbContext and DbSet is used for the Code First appraoch.Which enables a very clean and rapid development workflow.
Suppose we want to create a database called 'New Database' and two tables in that called 'State' and 'Country’. Then write the Model classes..
Go to Models right click on Models>>Add>>Class
Add a model class and name it as Country.cs
DbSet : Simplified alternative to Object Set and is used to perform CRUD operations against a specific type from the model.
DbContext and DbSet is used for the Code First appraoch.Which enables a very clean and rapid development workflow.
Suppose we want to create a database called 'New Database' and two tables in that called 'State' and 'Country’. Then write the Model classes..
Go to Models right click on Models>>Add>>Class
Add a model class and name it as Country.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.ComponentModel.DataAnnotations;
namespace
MvcApplication2.Models
{
public class Country
{
[Key]
public virtual int country_id {get;
set; }
[Required ]
public virtual string country_name {
get; set;}
}
}
Similarly add another class and named it as State.cs.
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.ComponentModel.DataAnnotations;
namespace
MvcApplication2.Models
{
public class State
{
[Key]
public virtual int state_id {get; set;
}
[Required ]
public virtual string state_name { get;
set;}
}
}
Add another Model class 'New Database.cs'
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Data.Entity;
namespace
MvcApplication2.Models
{
public class NewDatabase:DbContext
{
public DbSet Country { get; set; }
public DbSet State { get; set; }
}
}
Run
'Enable-Migrations' command from Package Manager Console
Open Configuration
file and set AutomaticMigrationsEnabled = true;
2. Then run 'Update-Database' command from Package Manager Console
2. Then run 'Update-Database' command from Package Manager Console
Now tables will get created as per given model.
No comments:
Post a Comment