EF Feature CTP5: Code First Walkthrough

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Code First to a New Database see https://msdn.com/data/jj193542

For Code First to an Existing Database see https://msdn.com/data/jj200620


 

We have released Entity Framework Feature Community Technology Preview 5 (CTP5) . Feature CTP5 contains a preview of new features that we are planning to release as a stand-alone package in Q1 of 2011 and would like to get your feedback on. Feature CTP5 builds on top of the existing Entity Framework 4 (EF4) functionality that shipped with .NET Framework 4.0 and Visual Studio 2010 and is an evolution of our previous CTPs.

This post will provide an introduction to Code First development. Code First allows you to define your model using C# or VB.Net classes, optionally additional configuration can be performed using attributes on your classes and properties or by using a Fluent API. Your model can be used to generate a database schema or to map to an existing database.

Mapping to an Existing Database

In CTP5 we have removed the need to perform additional configuration when mapping to an existing database. If Code First detects that it is pointing to an existing database schema that it did not create then it will ‘trust you’ and attempt to use code first with the schema. The easiest way to point Code First to an existing database is to add a App/Web.config connection string with the same name as your derived DbContext, for example;

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

This walkthrough is going to demonstrate Code First generating the database schema but the same principals apply to mapping to an existing database, with the exception of ‘8. Setting an Initialization Strategy’ which does not apply to existing databases.

 

1. Install EF CTP5

If you haven’t already done so then you need to install Entity Framework Feature CTP5.

 

2. Create the Application

To keep things simple we’re going to build up a basic console application that uses the Code First to perform data access:

  • Open Visual Studio 2010
  • File -> New -> Project…
  • Select “Windows” from the left menu and “Console Application”
  • Enter “CodeFirstSample” as the name
  • Select “OK”

 

3. Create the Model

Let’s define a very simple model using classes. I’m just defining them in the Program.cs file but in a real world application you would split your classes out into separate files and potentially a separate project.

Below the Program class definition in Program.cs I am defining the following two classes:

 public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CategoryId { get; set; }

    public virtual Category Category { get; set; }
} 

 

4. Create a Context

The simplest way to start using the classes for data access is to define a context that derives from System.Data.Entity.DbContext and exposes a typed DbSet<TEntity> for each class in my model.

We’re now starting to use types from CTP5 so we need to add a reference to the CTP5 assembly:

  • Project -> Add Reference…
  • Select the “.NET” tab
  • Select “EntityFramework” from the list
  • Click “OK”

You’ll also need a reference to the existing Entity Framework assembly:

  • Project -> Add Reference…
  • Select the “.NET” tab
  • Select “System.Data.Entity” from the list
  • Click “OK”

Add a using statement for System.Data.Entity at the top of Program.cs

 using System.Data.Entity;

Add a derived context below the existing classes that we’ve defined

 public class ProductContext : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

That is all the code we need to write to start storing and retrieving data. Obviously there is quite a bit going on behind the scenes and we’ll take a look at that in a moment but first let’s see it in action.

 

5. Reading & Writing Data

I’m padding out the Main method in my program class as follows:

 class Program
{
    static void Main(string[] args)
    {
        using (var db = new ProductContext())
        {
            // Add a food category 
            var food = new Category { CategoryId = "FOOD", Name = "Foods" };
            db.Categories.Add(food);
            int recordsAffected = db.SaveChanges();

            Console.WriteLine(
                "Saved {0} entities to the database, press any key to exit.",
                recordsAffected);

            Console.ReadKey();
        }
    }
} 

You can now run the application and see that the new category is inserted.

Where’s My Data?

DbContext by convention created a database for you on localhost\SQLEXPRESS. The database is named after the fully qualified name of your derived context, in our case that is “CodeFirstSample.ProductContext”. We’ll look at ways to change this later in the walkthrough.

Model Discovery

DbContext worked out what classes to include in the model by looking at the DbSet properties that we defined. It then uses the default Code First conventions to find primary keys, foreign keys etc. The full set of conventions implemented in CTP5 are discussed in detail in this Conventions Design Blog post.

 

6. Reading & Writing More Data

Let’s pad out the program we just wrote to show a bit more functionality. We are going to make use of the Find method on DbSet that will locate an entity based on primary key. If no match is found then Find will return null. We’re also making use of LINQ to query for all products in the Food category ordered alphabetically by name. Querying uses the exiting LINQ to Entities provider so it supports the same queries that are possible with ObjectSet/ObjectQuery in EF4.

I’m replacing the Main we wrote above with the following:

 class Program
{
    static void Main(string[] args)
    {
        using (var db = new ProductContext())
        {
            // Use Find to locate the Food category 
            var food = db.Categories.Find("FOOD");
            if (food == null)
            {
                food = new Category { CategoryId = "FOOD", Name = "Foods" };
                db.Categories.Add(food);
            }

            // Create a new Food product 
            Console.Write("Please enter a name for a new food: ");
            var productName = Console.ReadLine();

            var product = new Product { Name = productName, Category = food };
            db.Products.Add(product);

            int recordsAffected = db.SaveChanges();

            Console.WriteLine(
                "Saved {0} entities to the database.",
                recordsAffected);

            // Query for all Food products using LINQ 
            var allFoods = from p in db.Products
                            where p.CategoryId == "FOOD"
                            orderby p.Name
                            select p;

            Console.WriteLine("All foods in database:");
            foreach (var item in allFoods)
            {
                Console.WriteLine(" - {0}", item.Name);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
} 

 

7. Changing the Database Name

If you want to change the name of the database that is created for you, one of the ways to configure it is to alter the constructor on your DbContext, specifying the new database name.

Say we want to change the name of the database to “MyProductDatabase” we could add a default constructor to our derived context that passes this name down to DbContext:

 public class ProductContext : DbContext
{
    public ProductContext()
        : base("MyProductDatabase")
    { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
} 
Other Ways to Change the Database

There are a number of other ways to specify which database should be connected to. We’ll cover these in more detail in a separate post in the future.

  • App.config Connection String

    Create a connection string in the App.Config file with the same name as your context.

  • DbConnection

    There is a constructor on DbContext that accepts a DbConnection.

  • Replace the Default Convention

    The convention used to locate a database based on the context name is an AppDomain wide setting that you can change via the static property System.Data.Entity.Database.DbDatabase.DefaultConnectionFactory.

 

8. Setting an Initialization Strategy

In the next section we are going to start changing our model which in turn means the database schema needs to change as well. Currently there is no ‘out of the box’ solution to evolve your existing schema in place. Database evolution is something we are currently working on and a sample of the direction we are heading is provided in a recent design blog post.

There is however the opportunity to run some custom logic to initialize the database the first time a context is used in an AppDomain. This is handy if you want to insert seed data for test runs but it’s also useful to re-create the database if the model has changed. In CTP5 we include a couple of strategies you can plug in but you can also write custom ones.

Add a using statement for System.Data.Entity.Database at the top of Program.cs

 using System.Data.Entity.Database;

For the walkthrough we just want to drop and re-create the database whenever the model has changed, so at the top of the Main method in my Program class I’ve added the following code

 DbDatabase.SetInitializer<ProductContext>(
    new DropCreateDatabaseIfModelChanges<ProductContext>());

 

9. Data Annotations

So far we’ve just let EF discover the model using its default conventions but there are going to be times when our classes don’t follow the conventions and we need to be able to perform further configuration. There are two options for this; we’ll look at Data Annotations in this section and then the Code First Fluent API is covered in a separate post.

Let’s add a supplier class to our model:

 public class Supplier
{
    public string SupplierCode { get; set; }
    public string Name { get; set; }
}

And we also need to add a set to our derived context

 public class ProductContext : DbContext
{
    public ProductContext()
        : base("MyProductDatabase")
    { }

    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<Supplier> Suppliers { get; set; }
}

Now if we ran our application we’d get an InvalidOperationException saying “ EntityType 'Supplier' has no key defined. Define the key for this EntityType.” because EF has no way of knowing that SupplierCode should be the primary key for Supplier.

We’re going to use Data Annotations now so we need to add a reference:

  • Project -> Add Reference…
  • Select the “.NET” tab
  • Select “System.ComponentModel.DataAnnotations” from the list
  • Click “OK

Add a using statement at the top of Program.cs:

 using System.ComponentModel.DataAnnotations;

Now we can annotate the SupplierCode property to identify that it is the primary key:

 public class Supplier
{
    [Key]
    public string SupplierCode { get; set; }
    public string Name { get; set; }
}

The full list of annotations supported in CTP5 is;

  • KeyAttribute

  • StringLengthAttribute

  • MaxLengthAttribute

  • ConcurrencyCheckAttribute

  • RequiredAttribute

  • TimestampAttribute

  • ComplexTypeAttribute

  • ColumnAttribute

    Placed on a property to specify the column name, ordinal & data type

  • TableAttribute

    Placed on a class to specify the table name and schema

  • InversePropertyAttribute

    Placed on a navigation property to specify the property that represents the other end of a relationship

  • ForeignKeyAttribute

    Placed on a navigation property to specify the property that represents the foreign key of the relationship

  • DatabaseGeneratedAttribute

    Placed on a property to specify how the database generates a value for the property (Identity, Computed or None)

  • NotMappedAttribute

    Placed on a property or class to exclude it from the database

 

10. Validation

In CTP5 we have introduced a new feature that will validate that instance data satisfies data annotations before attempting to save to the database.

Let’s add annotations to specify that Supplier.Name must be between 5 and 20 characters long:

 public class Supplier
{
    [Key]
    public string SupplierCode { get; set; }

    [MinLength(5)]
    [MaxLength(20)]
    public string Name { get; set; }
}

Add a using statement at the top of Program.cs:

 using System.Data.Entity.Validation;

Let’s change the Main method to insert some invalid data, catch any exceptions and display information about any errors:

 class Program
{
    static void Main(string[] args)
    {
        DbDatabase.SetInitializer<ProductContext>(
            new DropCreateDatabaseIfModelChanges<ProductContext>());

        using (var db = new ProductContext())
        {
            var supplier = new Supplier { Name = "123" };
            db.Suppliers.Add(supplier);

            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var failure in ex.EntityValidationErrors)
                {
                    Console.WriteLine(
                        "{0} failed validation", 
                        failure.Entry.Entity.GetType());

                    foreach (var error in failure.ValidationErrors)
                    {
                        Console.WriteLine(
                            "- {0} : {1}", 
                            error.PropertyName, 
                            error.ErrorMessage);
                    }
                }
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}

If we run our application we will see the following displayed:

CodeFirstSample.Supplier failed validation

- Name : The field Name must be a string or array type with a minimum length of '5'.

Press any key to exit.

Summary

In this walkthrough we looked at Code First development using the EF Feature CTP5. We looked at defining and configuring a model, storing and retrieving data, configuring the database connection, updating the database schema as our model evolved and validating data before it is written to the database.

Fluent API

In addition to Data Annotations Code First also exposes a Fluent API to allow configuration, this is covered in a separate blog post.

Feedback & Support

As always we would love to hear any feedback you have on Code First by commenting on this blog post.

For support please use the Entity Framework Pre-Release Forum.

 

Rowan Miller

Program Manager

ADO.NET Entity Framework