About Me

indepth experience in developing RIA applications with C# Linq,WCF , Silverlight and JavaScript. Just help in delivering a robust business application in Silverlight for a large financial company.helped with architecture and coding. Participate in Codecamps as a presenter. This blog has no sense of order as it mainly a self help so I can reference things of my interest. my site http://www.sandkeysoftware.com has articles and videos by category

Monday, October 10, 2011

Entity Framework 4.1 Code First

I just installed and used Code First in my new project and love it. For an Object kind of person this is a great solution as when you are starting a new project we can work with objects and NOT tables as all u need to do is:

public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
public string Description { get; set; }
public List<State> States{ get; set; }
}

public class State
{

public int Id { get; set; }
public string Name { get; set; }
public string LongName { get; set; }
// public List<City> { get; set; }
}


Now we deine a DBContext that looks like :

public class CamAccess : DbContext
{
public DbSet<Country> Countrys { get; set; }
public DbSet<State> States { get; set; }
public DbSet<City> Citys { get; set; }
}

This is all we need to do and we when we write some Linq code to use Countrys as in:


public List<Country> GetCountrys()
{
CamAccess camdc = new CamAccess();
Database.SetInitializer<CamAccess>(new CamaccessInitializer());
List<Country> countrys = camdc.Countrys.ToList();
return countrys;
}


Then we have the tables Country and States generated for us including the Foreign keys. This will look something like this:




Note the call to Database.SetInitializer as this is great as it lets us not only recreate the tables as the model changes but populate the tables with data as the class looks like:

public class CamaccessInitializer : DropCreateDatabaseIfModelChanges<CamAccess>
{
protected override void Seed(CamAccess context)
{
Country c = new Country();
c.Name = "USA";
c.LongName = "United States";
context.Countrys.Add(c);
base.Seed(context);
}
}


0 comments: