Entity Framework Code-First and Code Only

Summary

In this blog post I’m going to explain the basics of Entity Framework code-first. I’ll show how to setup your context so that a database is not generated.

Code-First / Code-Only

If your database is already in place, then the most obvious method of using EF is to use Database First. This is where you start a new EDMX file and generate the code that matches your database. The problem with database first is that there are script files (tt files) based on the xml master file (edmx) that automatically generate your table and context code. If you make any database changes, you have to run the update on the edmx file and force the script files to regenerate your code. This can be a headache if you are deploying to a database that has a slightly different design than your test database. It can also be a serious problem when you are using version control since two different versions of the edmx file are impossible to reconcile. If you’re unsure what I’m talking about, right-click on the edmx file in your project and open as an xml file. Scroll through and observe how the data is stored.

In code-first, you define your context and tables manually in code. Then your database is generated when you run it the first time. This guarantees that your database is defined the match your EF code. The issue with this scheme is that you might already have a database designed and you might want more flexibility in your table definitions in code. Once instance is a situation where you might design a module (dll) that is used for a specific purpose in your program and only needs to query a few fields from a hand-full of tables. With code-first you can define exactly which fields you want to read and ignore any extra fields. However, if your database gets generated from the minimal context, you’ll end up with a database that doesn’t contain all the fields you need. This is where you need to disable the auto-generation part of code-first and turn your ORM into Code-Only.

Here’s an example of a code-first database with one simple table (you’ll need to add NuGet EF 6 to your project):

MyContext.cs file:

using System;
using System.Data.Entity;

namespace CodeFirstSample
{
    public class MyContext : DbContext, IDisposable
    {
        public MyContext()
            : base("My Connection String")
        {

        }

        // define tables here
        public DbSet<Room> Rooms { get; set; }
    }
}

Room.cs file:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CodeFirstSample
{
    [Table("Room")]
    public class Room
    {
        [Key]
        public int id { get; set; }
        public string Name { get; set; }
        public int RoomNumber { get; set; }
    }
}

In the above example one table named “Room” will get created in a database named according to the connection string. If you wish to prevent database creation from happening you can alter the context constructor like this:

public class MyContext : DbContext, IDisposable
{
    public MyContext()
        : base("My Connection String")
    {
        Database.SetInitializer<MyContext>(null);
    }

    // define tables here
    public DbSet<Room> Rooms { get; set; }
}

This will cause the context to skip the database generator.

When you’re laying out your code for your database it’s standard practice to create a sub-directory in your project and name it something like DAL (for data access layer) or similar. Then create your context cs file and all your table cs files in that directory. You can put all your tables in one file, but it’s easier to find code if your put one file per table and name the file the name of the table.

It’s also standard practice to pluralize the table name and leave the record instance or class name non-plural. In the example above the record is “Room” and the table is “Rooms”. If your table is named “Rooms” in your database, then you can alter the table attribute to match ([Table(“Rooms”)]).

The connection string can be a string, a variable or it can be read from your app.config or web.config file using the ConfigurationManager object like so:

private string ConnectionString = ConfigurationManager.ConnectionStrings["My Connection"].ToString();

You’ll have to add a reference to System.Configuration and put in a using for System.Configuration in order to use the ConfigurationManager object.

Leave a Reply