A Code First Example using Entity Framework 4
Here is a step by step Code First example using Entity Framework 4.
Firstly, make sure that the target framework of your project is set to .Net Framework 4:
Secondly, add a reference to Entity Framework in your project:
You can download the latest Entity Framework here: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=8363
Next, create some business classes. For this example I’m using Categories and Articles:
Article.cs
namespace CodeFirstExample
{
class Article
{
public long Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
}
Category.cs
using System.Collections.Generic;
namespace CodeFirstExample
{
class Category
{
public long Id { get; set; }
public string Name { get; set; }
public string Blurb { get; set; }
public ICollection<Article> Articles { get; set; }
public ICollection<Category> SubCategories { get; set; }
}
}
Then you need to create a DB context class:
MyDbContext.cs
using System.Data.Entity;
namespace CodeFirstExample
{
class MyDbContext : DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<Category> Categories { get; set; }
}
}
So now that we have that, here’s an example that will create your database and populate it with some data:
MyDbContext myDbContext = new MyDbContext();
myDbContext.Database.Connection.ConnectionString = “Data Source=localhost; Initial Catalog=Foo; Integrated Security=True;”;
new CreateDatabaseIfNotExists
Article articleAboutCats = new Article()
{
Title = “Cats”,
Content = “Something about cats.”
};
Article articleAboutDogs = new Article()
{
Title = “Dogs”,
Content = “Something about dogs.”
};
Article articleAboutElephants = new Article()
{
Title = “Elephants”,
Content = “Something about elephants.”
};
Category categoryForPets = new Category()
{
Name = “Pets”,
Blurb = “Animals you can keep as pets”,
Articles = new List<Article>() { articleAboutCats, articleAboutDogs }
};
Category categoryForAnimals = new Category()
{
Name = “Animals”,
Blurb = “Here are some animals”,
Articles = new List<Article>() { articleAboutElephants },
SubCategories = new List<Category>() { categoryForPets }
};
myDbContext.Categories.Add(categoryForAnimals);
myDbContext.SaveChanges();
You will find that the following database has been created for you:
… And that the tables have been populated:
Articles

Categories

