Sunday, May 13, 2012

Storage: Entity Framework

Entity framework is an ORM tool that maps POCO (Plain Old CLR Objects) to database tables
  • 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.
  1. 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
  2. Create database schema and generate EDM (use ADO.NET Entity Data Model in Visual Studio to create EDM from existing database)
using System.Data.Entity;

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 Framework
Model class: MyDataClass
Data context class: MyDataClassDbContext

MVC tooling creates CRUD action methods and views