I’m mostly a NHibernate user, but EF code first approach is intriguing, especially in situation where the customer prefer to use only Microsoft Stack libraries, thus EF 5.0 is a good approach to write quickly an Efficient data access module in really few clicks. Enabling EF5 on your own project is as simple as adding a reference with Nuget, go to package manager and type

install-package EntityFramework

and the game is done. Now you can start writing a simple class that will represent a table in the database.

public class Customer
{
    public Int32 Id { get; set; }

    public String Name { get; set; }

    public String Address { get; set; }
}

Now you need a class that inherits from DbContext to access the database and to expose all the classes you want to be saved/loaded from your database.

public class SampleContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

Now you should add a connection string to Sql server database you want to use, this is really simple because by convention the context you created looks for a connection string in configuration file named exactly as the class name, in this example SampleContext

  <connectionStrings>
    <add name="SampleContext" 
         connectionString="Database=Samples;Server=(local);Integrated Security=SSPI" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>

Actually I’ve no database called Samples in my local server so I wanted to create one with the correct structure to save my simple Customer class, but I can create automatically a database with the right schema to contain my data thanks to EF database-migrations. To enable migrations you should simple type Enable-Migrations on package manager console

PM> Enable-Migrations

Checking if the context targets an existing database…

Code First Migrations enabled for project FirstSteps.

Now you should have another folder called Migrations with a Configuration.cs files in your project, you can edit this file changing the value of AutomaticMigrationEnabled from false to true to enable automatic migrations. Now you can issue Update-Database command in your package manager console.

PM> update-database

Specify the ‘-Verbose’ flag to view the SQL statements being applied to the target database.

No pending code-based migrations.

Applying automatic migration: 201209150928099_AutomaticMigration.

Running Seed method.

Et voilà you have your database generated and ready to use. As you can see from Figure 1, the convention used is to create a table with the very same name of the DbSet properties exposed by your data context and a column for each property of the class.

image

Figure 1: Newly generated database with database-migration of EF5

Everything is created by convention over configuration, as an example if you have a property called Id, corresponding table column will be the primary key for the table, and if the value is an integer automatically the column is generated with Identity Set to true.

image

Figure 2: Id column was generated with Identity specification equal to true

Now you can access database simply creating an instance of SampleContext (do not forget to dispose it when you finished using it) and thanks to LINQ provider you can issue query on it, because all DbSet properties you expose are IQueryable so you can use to simply access all Customers with a simple Foreach.

 using (var context = new SampleContext())
 {
      Console.WriteLine("LISTING CUSTOMERS");
      foreach (var customer in context.Customers)
      {
           Console.WriteLine("Id: {0}t{1} ({2})", customer.Id, customer.Name, customer.Address);
       }
}

With really few lines of code you have created entity classes, corresponding database and can write/load data on it.

Alk.

Tags: ,

6 Responses to “Entity Framework 5.0, first steps and impressions”

  1. I think your last sentence “if you do not need the full power of NH” is misleading. In addition to being simple to use for quick & dirty project like in your example, EF is a pretty powerful ORM and perfectly suitable for enterprise development.

  2. I did not want to mean that EF is not suitable for enterprise development, it is a mature and really good framework that you can use for enterprise projects with no problem, but it has not the same feature-set of NH.

    NH is based on hibernate, a library that has years of history, and its feature set is richer than EF, it is also true that EF is evolving to reduce this gap, but at this version EF still misses some features, es: User Types.

    NH has also some interesting features like batching or futures that can reduce the number of roundtrip on database, to maximize performance.

    Alk.

  3. Agreed re batching (yes!! we need it in EF) and some other features like 2nd level caching and dynamic model types that are directly supported in EF (yet…though we finally have some workarounds). However, you are definitely missing a big piece of the puzzle if you are under the impression that EF only supports SQL Server. There are *many* database providers with EF support.

    I’ll send the rest of my comments privately. :)

  4. Thanks Julie for pointing out the mistake, I’ve updated my comment :). I wrote my answer too early in the morning :D and I wrote really incorrect stuff :(. It is LINQ to SQL that was born originally with only support for SQL Server :).

  5. haha … I have done the same myself. Written something down or asked a question and then looked at it and thought “WTH? I *know* that, I’ve written about it, I’ve told people about it. Wake up brain!”

Trackbacks/Pingbacks

  1. Entity Framework 5 Mapping