- Entity Framework is an ORM tool
- MVC has good scaffolding support for the Entity Framework. That is, MVC can automatically generate Controller CRUD actions and corresponding Views for EF entities.
- EF can be the Model for an MVC solution
Two ways to use EF.
public class MyDataClassDbContext : DbContext
{
public DbSet<MyDataClass> MyDataClass {get; set;}
}
Connection string can be specified in Web.Config
<connectionStrings>
<add name="MyDataClassDbContext"
connectionString="Data Source=|DataDirectory|MyData.sdf"
prroviderName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
// Create new object
MyPOCOClass myPoco = new MyPOCOClass();
myPoco.prop1 = "ddd";
myPoco.prop2 = "xxx"
MyPOCOClassDb db = new MyPOCOClassDb();
db.MyPOCOClass.AddObject( myPoco);
db.SaveChanges();
// Select and update
MyPOCOClassDb db = new MyPOCOClassDb();
MyPOCOClass myPoco = db.MyPOCOClass.SingleOrDefault(p => p.id == idToupdate);
myPoco.phone = "new dss";
db.SaveChanges();
// Select and delete
MyPOCOClassDb db = new MyPOCOClassDb();
MyPOCOClass myPoco = db.MyPOCOClasss.SingleOrDefault(p => p.id == idToupdate);
db.MyPOCOClasss.DeleteObject( myPoco);
db.SaveChanges();
Model class: MyDataClass
Data context class: MyDataClassDbContext
MVC tooling creates CRUD action methods and views
- Code First. Write POCO class and generate database tables (in App_Data folder) and EdmMetaData table to keep POCO classes in sync with the database schema
- Create database schema and generate EDM (use ADO.NET Entity Data Model in Visual Studio to create EDM from existing database)
public class MyDataClassDbContext : DbContext
{
public DbSet<MyDataClass> MyDataClass {get; set;}
}
Connection string can be specified in Web.Config
<connectionStrings>
<add name="MyDataClassDbContext"
connectionString="Data Source=|DataDirectory|MyData.sdf"
prroviderName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
// Create new object
MyPOCOClass myPoco = new MyPOCOClass();
myPoco.prop1 = "ddd";
myPoco.prop2 = "xxx"
MyPOCOClassDb db = new MyPOCOClassDb();
db.MyPOCOClass.AddObject( myPoco);
db.SaveChanges();
// Select and update
MyPOCOClassDb db = new MyPOCOClassDb();
MyPOCOClass myPoco = db.MyPOCOClass.SingleOrDefault(p => p.id == idToupdate);
myPoco.phone = "new dss";
db.SaveChanges();
// Select and delete
MyPOCOClassDb db = new MyPOCOClassDb();
MyPOCOClass myPoco = db.MyPOCOClasss.SingleOrDefault(p => p.id == idToupdate);
db.MyPOCOClasss.DeleteObject( myPoco);
db.SaveChanges();
Controller
Template: Controller with read/write actions and views, using Entity FrameworkModel class: MyDataClass
Data context class: MyDataClassDbContext
MVC tooling creates CRUD action methods and views