Quick & Dirty Code First with Entity Framework 6

I've never had the opportunity to work with the Code First approach in Entity Framework. All my work professionally has been against existing databases. However, I was given the opportunity to create two new applications for another business unit and decided it was time to try Code First.

Code First definitely feels strange to me, as I was brought up to design the database first and work from there. Computers are about data, right? So, why wouldn't you start there when building a new application. But, it's always good to try something new and perhaps gain a fresh perspective. Code First isn't something I expect to use much but, heck, why not give it a try?

Okay, first off, all those videos on YouTube where people rip through a Code First example in under ten minutes? Bah. In real life, I'm not working against an instance of LocalDb or SqlExpress -- I'm hitting an instance of a full-fledged SQL Server engine on a server somewhere deep in the bowels of the corporate data center. Second, I'm not working with a trivial model, like "Dog". Third, most examples and tutorials out there are on Entity Framework versions prior to 6. What various demos on the web did in 10 minutes took me about 2 hours to figure out and get running.

More for my sake than yours, I've sketched out below the roughest and most stripped down steps for creating an Entity Framework 6 Code First application.

Quick & Dirty Entity Framework Code First Example

Create a Domain library.

Add your models to the Domain library.

Create a Repository library.

Use NuGet to add a reference to Entity Framework 6.

Add a reference to the Domain library.

Add a new class to the Repository, naming it …Context. The class should inherit from the DbContext class. Below is a brief example:

using System.Data.Entity;
using  GasCommodity2.Domain;

namespace GasCommodity2.Repository
{
    public class GasCommodityContext : DbContext
    {
       
    }
}

Add a public property of type DbSet<T> for each model in your domain:

using System.Data.Entity;
using  GasCommodity2.Domain;

namespace GasCommodity2.Repository
{
    public class GasCommodityContext : DbContext
    {
        public DbSet<Adjustment> Adjustments {get; set;}
        public DbSet<Contract> Contracts {get; set;}
        public DbSet<Customer> Customers {get; set;}
        public DbSet<Invoice> Invoices {get; set;}
        public DbSet<Location> Locations {get; set;}
        public DbSet<Payment> Payments {get; set;}
        public DbSet<Plan> Plans {get; set;}
        public DbSet<Transaction> Transactions {get; set;}
    }
}

Add a constructor. Use the constructor to set value of the property UseDatabaseNullSemantics to true:

using System.Data.Entity;
using  GasCommodity2.Domain;

namespace GasCommodity2.Repository
{
    public class GasCommodityContext : DbContext
    {
        public DbSet<Adjustment> Adjustments {get; set;}
        public DbSet<Contract> Contracts {get; set;}
        public DbSet<Customer> Customers {get; set;}
        public DbSet<Invoice> Invoices {get; set;}
        public DbSet<Location> Locations {get; set;}
        public DbSet<Payment> Payments {get; set;}
        public DbSet<Plan> Plans {get; set;}
        public DbSet<Transaction> Transactions {get; set;}

        public GasCommodityContext()
        {
            Configuration.UseDatabaseNullSemantics = true;
        }
    }
}

By setting this property to true you prevent an error where using the DbContext returns a failure due to a null parameter. This issue should only affect versions of Entity Framework prior to 5 but I’ve experienced it with version 6. This setting squashed the problem.

Create a console application. Add references to the Domain and Repository libraries. Also, use NuGet to add a reference to Entity Framework 6. If you don’t add a reference to Entity Framework 6, then critical DLLs will not be copied to the output folder when the solution is built. This is a known issue with Entity Framework.

Update the app.config file to use a connection string pointing to an instance of SQL Server. By default, Entity Framework will, with Code First, create the database in a local instance of LocalDb or SqlExpress. Your app.config file should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add
      name="GasCommodityContext"
      connectionString="Data Source=plssqld-dc01-02;Initial Catalog=GasCommodity;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="'Data Source=plssqld-dc01-02;Initial Catalog=GasCommodity;Integrated Security=True'"/>
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

The primary changes are
  • the connection string
  • the default connection factory within the EntityFramework section
  • the provider within the EntityFramework section


Edit program.cs (in the console application project). For instance, add the code necessary to add an object to the repository:

using System;
using GasCommodity2.Domain;
using GasCommodity2.Repository;

namespace GasCommodity2.ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer customer = new Customer();
            customer.FirstName = "Bugs";
            customer.LastName = "Bunny";
            customer.CreatedDate = DateTime.Now;
            using (GasCommodityContext context = new GasCommodityContext())
            {
                context.Customers.Add(customer);
                context.SaveChanges();
            }
            Console.WriteLine("CustomerId = " + customer.CustomerId);
        }
    }
}

Run the program.

Wait. The console will appear idle while the program and in turn Entity Framework looks for the database, doesn’t find it, generates the script to create the database, runs that script, and then adds the new item to the database.

Examine the database engine and note the new database plus the record added to the appropriate table.






Comments

Popular posts from this blog

Using Reference Aliases

List of Visual Studio Keyboard Shortcuts