Skip to content

Instantly share code, notes, and snippets.

@timyhac
Last active November 21, 2020 01:59
Show Gist options
  • Save timyhac/a252dc52afa571934dfa8bb442cfcad6 to your computer and use it in GitHub Desktop.
Save timyhac/a252dc52afa571934dfa8bb442cfcad6 to your computer and use it in GitHub Desktop.
How to add Entity Framework Database migrations on startup
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
// Other classes can found at https://docs.microsoft.com/en-us/ef/core/get-started/overview/first-app
// Requires generation of migrations using ef tools
// Standalone, this is a bad idea
// Use this carefully, see https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying?tabs=dotnet-core-cli#apply-migrations-at-runtime
namespace EntityFrameworkTraining
{
public static class MigrationManager
{
public static IHost MigrateDatabases(this IHost host)
{
using(var scope = host.Services.CreateScope())
{
using(var ctx = scope.ServiceProvider.GetRequiredService<BloggingContext>())
{
ctx.Database.Migrate();
}
}
return host;
}
}
class Program
{
static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureServices(services => {
services.AddDbContext<BloggingContext>();
})
.Build()
.MigrateDatabases();
using(var db = new BloggingContext())
{
Console.WriteLine("Inserting a new blog");
db.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
db.SaveChanges();
// Read
Console.WriteLine("Querying for a blog");
var blog = db.Blogs
.OrderBy(b => b.BlogId)
.First();
// Update
Console.WriteLine("Updating the blog and adding a post");
blog.Url = "https://devblogs.microsoft.com/dotnet";
blog.Posts.Add(
new Post
{
Title = "Hello World",
Content = "I wrote an app using EF Core!"
});
db.SaveChanges();
// // Delete
Console.WriteLine("Delete the blog");
db.Remove(blog);
db.SaveChanges();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment