Minimum Code First Setup

This is the absolute minimum you need to get started with Code-First.

Before I start I assume you have Visual Studio, are familiar with NuGet and have access to some version of SQL Server.

First use NuGet to install EntityFramework. Now you need 2 classes to get started. One to represent the database and the other to represent your table:

public class PeopleDb : DbContext {
    public DbSet<Person> People { get; set; }
}

public class Person {
    public Guid Id { get; set; }
    public string Name { get; set; }
}

Here is a sample of saving an entity:

var db = new PersonDb();
db.People.Add(new Person {
    Id = Guid.NewGuid(),
    Name = "John",
});
db.SaveChanges();

And here is a sample of querying it.

var db = new PersonDb();

foreach (var person in db.People) {
    Console.WriteLine(person.Name);
} 

Finally if you want the database schema to update automatically as you make changes to your model you can add the following code to the start of your application:

var migratorConfig = new DbMigrationsConfiguration();
migratorConfig.AutomaticMigrationsEnabled = true;
//migratorConfig.AutomaticMigrationDataLossAllowed = true;
new DbMigrator(migratorConfig).Update();

For more detail information about that code snippet check out the blog post by Joshua Mouch: 

Entity Framework Code First Migrations: Executing migrations using code, not PowerShell commands.

Uncomment the line AutomaticMigrationDataLossAllowed if you are prototyping don’t care if you loose data when you rename or remove fields from your entity objects.

That’s it you are done, you don’t even need a connection string. Code-First will automatically create the database when you access the database from your code. It will automatically look for SQL Server at .\SQLEXPRESS and it will name the database based on the name of your class: Namespace.ClassName.

You can specify a connection string if you want control over which server to use and what the database will be named. Here is an example:

<connectionStrings>
<add 
 name="PersonDb" 
 connectionString="Server=.;Database=People;Trusted_Connection=True;"
 providerName="System.Data.SqlClient" />
</connectionStrings>

Whichever portion of the connection string is omitted is assumed. For example if you leave out the Server it will either create a LocalDb or look for .\SQLEXPRESS and if you leave out the Database it will assume Namespace.ClassName. Note the name of the connection must match the name of your DbContext.

Note on this blog post I mention how to update the schema using a code snippet, this is very convenient when creating a prototype, but probably a bad idea for production code. The more customary approach to updating the database schema when working with the entity framework is to use the Package Manager Console. And issue the command Enable-Migrations –EnableAutomaticMigration to enable “automatic” migration for the project. And then use the Update-Database command whenever you make a change to the model.

Leave a Reply

Your email address will not be published. Required fields are marked *