Skip to content

Instantly share code, notes, and snippets.

@rowanmiller
Last active February 29, 2016 23:58
Show Gist options
  • Save rowanmiller/d3bef12da9bdf690d470 to your computer and use it in GitHub Desktop.
Save rowanmiller/d3bef12da9bdf690d470 to your computer and use it in GitHub Desktop.
EF6.x | Same context instance to different databases
using System;
using System.Data.Entity;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
private static string connection_one = "Server=(localdb)\\mssqllocaldb;Database=Blogging_One;Trusted_Connection=True;";
private static string connection_two = "Server=(localdb)\\mssqllocaldb;Database=BLogging_Two;Trusted_Connection=True;";
static void Main(string[] args)
{
SetupTestData();
using (var db = new TestContext())
{
db.Database.Connection.ConnectionString = connection_one;
var blog = db.Blogs.First();
blog.Url += "/modified";
db.Database.Connection.ConnectionString = connection_two;
db.SaveChanges();
}
}
private static void SetupTestData()
{
var blog = new Blog { Url = "http://sample.com", BlogId = new Guid() };
using (var db = new TestContext())
{
db.Database.Connection.ConnectionString = connection_one;
db.Database.CreateIfNotExists();
db.Blogs.Add(blog);
db.SaveChanges();
}
using (var db = new TestContext())
{
db.Database.Connection.ConnectionString = connection_two;
db.Database.CreateIfNotExists();
db.Blogs.Add(blog);
db.SaveChanges();
}
}
}
public class TestContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public Guid BlogId { get; set; }
public string Url { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment