Introduction to Entity Framework Code First

Introduction

Entity Framework (EF) allows you to program against a model instead of dealing with a database directly. In EF 4.0 (that ships with .NET 4.0) you typically design a model from an existing database visually, using a designer provided for that purpose. EF 4.1 builds on top of what EF 4.0 provided and allows you to create models directly at code level. That means instead of creating any database and then using a designer to define models, you create plain .NET classes and then use EF 4.1 techniques to make them EF models. This approach is referred as Code First because you focus on the source code of the model classes first. Once the models are ready Code First can also generate database tables out of those model classes. In this tutorial you will learn the basics of developing an application using Entity Framework Code First.

NOTE:
In order to work through the examples illustrated in this article you must have Visual Studio 2010 with Entity Framework 4.1 installed on your computer. You can download and install EF 4.1 here.

What is Code First?

EF 4.0 provides two approaches for working with entities, viz. Database First and Model First. In the former case you design a database before starting your application development. Then you use Entity Data Model Designer of Visual Studio to design a data model visually by dragging and dropping tables from the database onto the designer (see Figure 1). In the case of Model First development you use Entity Data Model Designer to design data model classes manually (see Figure 2). You then specify the database connection to be used in the application. In any case you use Entity Data Model Designer to generate your data model classes.

Designing a model with Database First approach
Figure 1: Figure 1 : Designing a model with Database First approach

Designing a model with Model First approach
Figure 2: Designing a model with Model First approach.

EF 4.1 offers one more way of generating model classes - Code First. In the Code First approach you won't use any designer at all. You will create plain .NET Framework classes and then use certain attributes and associated techniques to make them Entity Framework Data Models (see Figure 3).

Creating a model with Code First
Figure 3: Creating a model with Code First

When you run the application that makes use of the Code First technique for the first time the EF will create a new SQL Express database, based on the model classes, for you. You can, of course, skip this step and specify your existing database if you so wish.

Now that you have some idea about Code First, let's develop a sample application, step-by-step, that illustrates the entire process. In the example that follows you will be dealing with a data model that represents a blog post. The actual data resides in a SQL Server table named BlogPosts. You can then read-write data to the table using the model class.

Creating a Model

Let's assume that you are dealing with a data model that represents a blog post and a blog post category. To begin developing the models, create a new project of type Class Library and name it CodeFirstLib. The class library project will contain two model classes, viz. BlogPost and Category. These classes are shown below:

public class BlogPost
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }
    public virtual Category Category { get; set; }
}
 
public class Category
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<BlogPost> BlogPosts { get; set; }
}

The BlogPost class defines five properties namely Id, Title, Content, PublishDate and Category. Notice that Category property represents a foreign key. The Category class has three properties - Id, Name and BlogPosts. The BlogPosts property is a collection property because there can be multiple blog posts belonging to a single category. Remember that under the default scheme, the property that represents a primary key should have data type of int or Guid. In the former case, EF 4.1 will translate the property as an identity column in the database and in the latter case a Unique Identifier. You can, of course, customize this behavior using certain attributes as we will discuss later.

Creating a Data Context

Now that your model classes are ready, let's proceed to creating a data context. A data context allows you to query and work with the entity data in your application. A data context is a class that inherits from DbContext base class. The following class shows how a data context for our example looks:

 public partial class BlogContext : DbContext
{
  public BlogContext():base("BlogDb")
  {
  }
 
  public DbSet<BlogPost> BlogPosts { get; set; }
  public DbSet<Category> Categories { get; set; }
 
}

The BlogContext class inherits from DbContext base class. The constructor of the BlogContext class calls the base class constructor and passes a desired database name to it. When you run the application for the first time a database with this name is created for you. If you do not pass this information, the name of the database will be the same as the fully qualified name of the DbContext class (CodeFirstLib.BlogContext in our example).

The BlogContext class defines two public properties, viz. BlogPosts and Categories. These properties are of type DbSet. The DbSet class represents an entity set (in other words a database table) on which CRUD (Create, Read, Update, Delete) operations can be performed.

Testing Database Generation

To test the code you wrote so far, add a new Console Application to the same solution and add a reference to the CodeFirstLib project you just created. Then key-in the following code in the Main() method.

using (var db = new BlogContext())
{
    Guid id = Guid.NewGuid();
 
    var cat = new Category { Id = id, Name = "ASP.NET" };
    var post = new BlogPost { Title="Title1", Content="Hello World!", PublishDate=new DateTime(2011,1,1), Category=cat};
 
    db.Categories.Add(cat);
    db.BlogPosts.Add(post);

    int i = db.SaveChanges();
}
 
Console.WriteLine("{0} records added...", i);
Console.ReadLine();

The above code creates a new instance of BlogContext data context. It then creates an instance of Category and BlogPost classes respectively. The newly created entity instances are added to the DbSets and finally SaveChanges() method of the data context is called. The SaveChanges() method persists the entity data into the database tables and returns the number of records affected by the operation.

Now run the Console application. Since this is your first ever run of the application, EF will create the database and tables for you using SQL Express running on your machine. The name of the database created will be BlogDb (as specified in data context constructor) and two tables - BlogPosts and Categories - will also be created.

Database and tables created after the first run of the application
Figure 4: Database and tables created after the first run of the application.

Notice how Id column of BlogPosts and Categories table is marked as primary key. Also, notice that BlogPosts table has a foreign key (Category_Id) defined.

Recreating the Database with Every Run

During the testing phase you may want to create the database under consideration with each run of your application so that your application runs on a clean slate. Additionally, you may want to add some test data into the database while it is being created. Database re-creation is desirable under one more scenario - when entities (and thus tables) change during development. By default EF will create the database only during the first run of the application and there after use the same database for further operations. To alter this behavior you need to create what is known as a database initializer. The initializer typically takes a form of a class inherited from DropCreateDatabaseAlways class. As the name suggests, the DropCreateDatabaseAlways class always re-creates the database. The following code shows BlogContextInitializer that does just that.

NOTE:
You can also make use of DropCreateDatabaseIfModelChanges class in which case the database will be re-created when models change.

public class BlogContextInitializer : DropCreateDatabaseAlways<BlogContext>
{
    protected override void Seed(BlogContext context)
    {
        Category cat1 = new Category { Id=Guid.NewGuid(), Name=".NET Framework" };
        Category cat2 = new Category { Id = Guid.NewGuid(), Name = "SQL Server" };
        Category cat3 = new Category { Id = Guid.NewGuid(), Name = "jQuery" };
 
        context.Categories.Add(cat1);
        context.Categories.Add(cat2);
        context.Categories.Add(cat3);
 
        context.SaveChanges();
 
    }
}

The BlogContextInitializer class inherits from DropCreateDatabaseAlways base class and overrides Seed() method. The Seed() method adds some sample data to the database being created. In the above example you add three categories. Once the initializer is ready you need to add the following line of code in the Main() method.

static void Main(string[] args)
{
    Database.SetInitializer<BlogContext>(new BlogContextInitializer());
    ...
    ...

Now you will find that with every run the database is re-created and the Categories table is populated with sample data.

Using an Existing Database with Code First

In the above example, you allowed EF to create a database for you. In many cases you may want to use an existing database rather than creating a new one. This can be accomplished by specifying a database connection string in the application configuration file (or web.config file) as shown below:

<configuration>
  <connectionStrings>
    <add
      name="BlogDb"
      providerName="System.Data.SqlClient"
      connectionString="Server=.\SQLEXPRESS;Database=BlogDb;Trusted_Connection=true;"/>
  </connectionStrings>
</configuration>

Note that the name of the database connection string as mentioned in the <connectionStrings> section and the one specified in the data context class must match. If you do not specify anything in the data context class, then the name of the data context itself is assumed. For example, we passed string "BlogDb" in the data context class (BlogContext) in which case EF will first check in the configuration file whether any connection string with name BlogDb is defined; if so, EF will use the database as mentioned in the connection string for further operation. If there is no connection string defined it will proceed and create a new database with name BlogDb under local SQL Express installation. If you do not pass anything to the base class from the data context class then EF will first look for a database connection string with name BlogContext in the configuration file and if found will use that database for further operations.

Using Data Annotations to Specify Table and Key Information

In the above example we used default conventions of EF while creating entity classes. You can use certain data annotations to customize this behavior. For example, consider the BlogPost and Category classes shown below that essentially do the same job as in the previous case but use some data annotation attributes to specify table name, primary key and foreign key information.

[Table("BlogPosts")]
public class BlogPost
{
    [Key]
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public DateTime PublishDate { get; set; }
 
    [ForeignKey("Category")]
    public Guid CategoryId { get; set; }

    public virtual Category Category { get; set; }
}
 
[Table("Categories")]
public class Category
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<BlogPost> BlogPosts { get; set; }
}

As you can see, the [Table] attribute explicitly specifies the name of the table (BlogPosts and Categories respectively). On the same lines, [Key] and [ForeignKey] attributes specify primary key and foreign key information respectively.

Summary

The Entity Framework Code First allows you to make use of EF features directly at code level, i.e. without designing any Entity Data Models. This way you create entity classes as plain C# classes. You then define a data context by inheriting from DbContext class. Additionally, you can also use data annotation attributes such as [Key], [ForeignKey] and [Table] to specify the respective pieces of information explicitly. By default, EF creates a database under SQL Express when the application is run for the first time. You can alter this behavior by creating your own database initialization strategy. You can also use an existing database instead of creating a new one by specifying database connection string in the configuration file.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Related Articles

Downloads

Comments

  • mankind cup 2014 brazil soccer jerseys power commitment coming this biggest soccer party.

    Posted by Merejensejage on 06/17/2013 06:33pm

    Before he left the sideline, Harris seemed to be telling Bears coach Lovie Smith that Lutui had kneed him. But there's no excuse for punching a player who is on the ground. Harris just got ejected on the fourth play of the Bears' game against Arizona for a blatant, ridiculous punch of Cardinals guard Deuce Lutui. The two had begun scuffling on the [url=http://worldcupsoccerfacts.info/]wholesale soccer jerseys[/url] previous play. After the fourth play was whistled dead, Harris was lying on top of Lutui and delivered a closed-fist punch through Lutui's facemask a few yards away from the Cardinals bench. It was a tough opening drive for the Bears, who also lost middle linebacker Hunter Hillenmeyer to [url=http://worldcupsoccerfacts.info/]2014 world cup soccer jerseys[/url] another injury. His status is uncertain, but for now the Bears are using Nick Roach in the middle and Jamar Williams on the strong side. Posted by ESPN.com's Kevin Seifert CHICAGO -- Just when you thought Tommie Harris couldn't become a more bizarre character in Chicago, he comes up with another stunt.Harris Referee [url=http://worldcupsoccerfacts.info/]wholesale soccer jerseys[/url] Ed Hochuli immediately ejected Harris, who was replaced by Israel Idonije. Harris has hardly made an impact this season, as we've documented repeatedly, but now he's given the Cardinals a huge early emotional advantage as well. The Cardinals lead 7-0 after Larry Fitzgerald beat Charles Tillman for an 11-yard touchdown reception.

    Reply
  • sphere cup 2014 brazil soccer jerseys surroundings politesse coming this biggest soccer party.

    Posted by Merejensejage on 06/15/2013 08:12pm

    The Cincinnati Bengals completed their second preseason game on Sunday. Cincinnati lost to the New York Jets, 27-7. Here are some observations: The Bad Overall, the Bengals need to start better. They have been outscored 41-10 in the first half when starters get a majority of the playing time. Yes, it's only the preseason. But it doesn't look good when Cincinnati's first team routinely fails to set the tone. The Bengals aren't the Pittsburgh Steelers or Green Bay Packers. Cincinnati is a young team that needs to show something in the preseason to gain momentum and confidence for the regular season. Cincinnati's first-team defense made some strides this week. The offense struggled early (we will get to that later). [url=http://worldcupsoccerfacts.info/]2014 world cup jerseys[/url] But the defense did a decent job [url=http://worldcupsoccerfacts.info/]Cheap [url=http://worldcupsoccerfacts.info/]brazil world cup jerseys[/url] soccer jerseys[/url] of keeping the game close in the first half. Cincinnati's first-team defense gave up 10 [url=http://worldcupsoccerfacts.info/]brazil world cup jerseys[/url] points before most of the starters were pulled. The Jets had a lengthy touchdown drive before halftime against a mix of Bengals starters and backups. Cincinnati's offense does not look ready [url=http://worldcupsoccerfacts.info/]Cheap soccer jerseys[/url] for Week 1. This unit is just too sloppy. Cincinnati's first three possessions ended like this: an Andy Dalton interception, a 17-yard loss on a fumble that forced a punt and another interception. The timing just looks off, although Cincinnati's starting offense eventually warmed up at the end and scored its first touchdown of the preseason. The Good Punter Kevin Huber may be an early candidate for Bengals MVP. He is having a great preseason and booted several more impressive punts Sunday against the Jets. Huber had nine punts for 424 yards, which is a stellar 47.1 average.

    Reply
  • Cuál es la diferencia entre en el oído y sobre el oído

    Posted by cheneason on 06/04/2013 04:58pm

    [url=http://www.beats-by-dr-dre-2013.webstarts.com/]beats by dr dre[/url] Beats By Dr. Dre Beats Wireless har annonceret et trådløst Bluetooth-headset. Dette er udformningen af den populære Solo HD og kan let kobles med en smartphone eller tablet. Den nye model er også udstyret med ControlTalk, med en mikrofon i øret og alle nødvendige kontroller. Beats By Dr. Dre introducerer Beats trådløse Bluetooth hovedtelefoner Beats By Dr. Dre Beats introducerer den trådløse Bluetooth-hovedtelefoner lytteren fuld musikalsk frihed. [url=http://www.comprarbeatsbaratos.weebly.com/]Comprar beats baratos[/url] Producenter frembringer deres egne beats på nettet åbner ubegrænsede samarbejdsmuligheder med hensyn til designere på et stramt budget. Den særlige udseende tilgængelig er utallige der en bred vifte af friske rekorder på markedet hver dag derude sted. I tilfælde af at du synes at købe overgår, anmeld af din web selskabet samt høre deres varer. Du er i stand til at Google eller måske Ask tilstande såsom “internet-producenter” eller “køb er bedre end online” og masser af troværdige producent internetsider vil helt sikkert producere.En anden tendens jeg opdager i trap rekorder kunne være den store brug af rumklang omkring den primære enhed. Der er typisk en enkelt pind ud værktøj put, der har en velvoksen reverb effekt sige for eksempel en grand violin, guitar, samt synth. I de fleste tilfælde en let melodi, der gentager flere gange samt modulerer op eller ned. Processen mod kaos er meget simpelt, så prøv ikke at under vurdere de grunde, der kan placeres i dette. beats [url=http://www.auriculares-beats.webs.com/]Beats by dr dre españa[/url] Hvis man ville præcisere, hvad præcist udrette audio transskription tjenesteudbydere samt transskribere tjenester udføre, svaret er, som de fuldføre opgaven med at konvertere musik information i elektronisk fil info. Hvis det overhovedet er muligt, kan en uddannet transcriptionist lytte til lyd tape løsninger, der har brug for at konvertere, og derefter dokumentere dem i en elektronisk digital fil, der kan helt sikkert være en sætning fil eller tilknyttede fil formatering.

    Reply
  • It's been a energetic week on account of enchiridion shared retailer|stuff exit online

    Posted by SosseRourreli on 06/03/2013 12:31pm

    The Best Laid Plans ELLE The Best Laid PlansMarch 26 12:02 PMby ELLE 0 Comments laughing hysterically at god-knows-what in my unplanned for red dress So I planned on wearing this little vintage gold backless minidress on my birthday forever. Or, you know, for the past couple of weeks. [url=http://savebigshopping.com/]http://savebigshopping.com/[/url] Which is a pretty long time to plan on wearing something. Anyway, as I was getting ready to meet my friends for dinner on Saturday night, I pulled it on over my head, looked in the mirror....and realized that it was all wrong. Way too glittery and gold for a dinner [url=http://savebigshopping.com/]coach factory[/url] and some East Village bar-hopping. So after a few panicked moments during which the entire contents of both of my closets ended up on my bedroom floor, I [url=http://savebigshopping.com/]coach factory[/url] settled on a tomato-red v-neck dress that I've had for years. Kind of a let-down but it just goes to show how even the simplest of plans can go totally awry. And then there are the bigger categories of [url=http://savebigshopping.com/]coach outlet[/url] plans. Like [url=http://savebigshopping.com/]coach factory[/url] the ones we make on New Year's Eve when we sit down and plan out who we're going to be in the next year, how we're going to be better, what we're going to do and when. Or for me, that always happens on birthdays. Another year older just seems more urgent to me than a new calendar year. So instead of New Year's resolutions, I make birthday resolutions. I come up with a game plan for what I'm going to accomplish in the year's time before I'm yet ANOTHER year older. My mental checklist of goals this year went something like this: Finish novel ASAP. Stop dating ridiculously inappropriate [url=http://savebigshopping.com/]coach factory[/url] men. Stop dating ridiculously unavailable men. Stop smoking socially. Run five miles a day and eat less. Or at least eat healthier. So, okay, I broke two out of five about, oh, three hours into my birthday but I, um....did my best....? ANYway, I'm fully aware that most of these things are probably going to take a little more time and growing up than a year can provide but I just can't help making my little lists. I'm sure we all have a plan, a mental checklist that will comprise our perfect lives. But I'm also sure that no matter how diligently we design and classify and organize, it's pretty futile. Because we can strategize all we want, but when it comes down to it, they're just blueprints that don't take into account the unexpected. The unforeseen things, people, and events that can derail even the best laid plans. But we do the best we can. And in the end, that's all anyone can do. And besides, sometimes, those unexpected things, those blindsiding moments that you never see coming–sometimes those are exactly the ones that are really worth living for.

    Reply
  • Lightweight bright – Nike Let off TR Attack in shoot up 2013 3 series

    Posted by Tufffruntee on 04/22/2013 10:57am

    Nike Emancipated TR Fit 3 salient features is to use the additional scheme: Nike Self-ruling 5 soles improved bending Gouge; stylish tractor pattern making training more focused when; lighter weight, the permeability is stronger, and more in fashion shoe designs not only make shoes [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] more serene wearing, barefoot training have compassion for incline, but also more in fashion appearance. Nike Manumitted TR Fit 3 provides first-class lateral solidity, you can be suffering with the legs in the lap boost during training. Eager vamp superiority breathable mesh, lower suds's consonant lay out can be [url=http://markwarren.org.uk/property-waet.cfm]nike air max 90[/url] seen from stem to stern it. Lightweight, ragged, piddling bubbles means habituated to past merest only one seams, more flexible, support is stronger. Lack more mainstay, factor of a training irritate, froth make inaccessible in more parts of the need championing flexibility, bubble loose. Use two-ply patois moisture wicking mock materials, tiresome on your feet, mitigate maintenance feet tiring and comfortable. Phylite [url=http://northernroofing.co.uk/roofins.cfm]nike free run 3[/url] midsole offers lightweight surprise unchanging, superior durability and even outsole can do to greatly lower the total load of the shoe. Qianzhang pods on the outsole and heel-shaped Na媣e rubber enhances the shoe multi-directional drag on sundry surfaces.

    Reply
  • More concessions with herveleger, more surprise!

    Posted by rightmrcas on 03/26/2013 01:25am

    herve leger outlet herve leger outlet herve leger sale herve leger outlet herve leger outlet herve leger outlet herve leger swimsuit iphone 5 outlet iphone unlocked for sale iphone 5 unlocked

    Reply
  • Thanks a lot!

    Posted by Quilin on 12/12/2012 09:20am

    I was trying to get in with Entity framework, but all the articles i found was a bit useless to me as front-developer. So that's the first one that gave me result, so thank you very much.

    Reply
  • DropCreateDatabaseAlways not there is EF 4.1

    Posted by praveen on 04/09/2012 06:43am

    as per DropCreateDatabaseAlways class is not there in EF 4.1. it is a feature of EF 5.0 beta version.

    Reply
  • DropCreateDatabaseAlways is not available in EF 4.1

    Posted by Praveen on 04/09/2012 06:42am

    I am using EF4.1 but DropCreateDatabaseAlways seems to be part of EF 5.0 beta feature as per msdn http://msdn.microsoft.com/en-us/library/gg679481(v=vs.103).aspx How to do the same for 4.1?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds