Kristoffer Karlsson

Feb 1, 2017

3 min read

Getting started with .NET Code First and Migrations, Step by Step guide

Database 100% from code

Setup the Project

  • Download EntityFramework from Nuget

Create some entities

[Table("Blogs")]
public class Blog
{
[Key]
public int ID { get; set; }
[Required, StringLength(50)]
public string Title { get; set; }
[Required, StringLength(50)]
public string BloggerName { get; set; }
public virtual ICollection<Post> Posts { get; set; } public Blog()
{
Posts = new HashSet<Post>();
}
}

Note the DataAnnotiations (Attributes).
You can read more about DataAnnotations here :
https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx

[Table("Posts")]
public class Post
{
[Key]
public int ID { get; set; }
[Required, StringLength(50)]
public string Title { get; set; }
[Required]
public DateTime DateCreated { get; set; }
[Required, StringLength(5000)]
public string Content { get; set; }
[Required]
public int Blog_ID { get; set; }
[ForeignKey("Blog_ID")]
public virtual Blog Blog { get; set; }
}

Dont forget to add the connection string!

<connectionStrings>
<add name="MyDb" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\MyDb.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

DbContext

public class MyDbContext : DbContext
{
public virtual DbSet<Blog> Blogs { get; set; }
public virtual DbSet<Post> Posts { get; set; } public MyDbContext() : base("MyDb"){ }
}

Create the Database

static void Main(string[] args)
{
var dbContext = new MyDbContext();
dbContext.Database.CreateIfNotExists(); Console.WriteLine("Done");
Console.ReadLine();
}
Your database has now been created and should have the following two tables.

Update the Database with migration code

public bool Published { get; set; }

Now is when the magic starts to happen. Go your Package Manager Console in visual studio and run :

Enable-Migrations -ProjectName <YOUR_PROJECT_NAME> -ContextTypeName <YOUR_CONTEXT_NAME>

Note how a new folder ‘Migrations’ is added to your project.

Now run :

Add-Migration MyMigration1

Note how a new file has been created. This file tells us exactly whats been added to our code first model and what needs to be added to our database.

Now run :

Update-Database

Take a look at your database and you will see that your new property Published has been added!

This is how easy it is to update your database with migration files in .NET Code first :)

I hope you find this article helpful and don’t forget to follow me on twitter.

BTC

ETH