EntityFramework 7 Multi-Db

In simple apps, majority of the times one apps will only use 1 db (master) (read and write) and cluster (read only) which is good for the reporting.

We need to have 2 DbContext

    public class ContextOne : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            builder.UseSqlServer(@"Server=VT13-PC\SQLEXPRESS;Database=ContextOne;User ID=sa;Password=1234;Max Pool Size=2000;Min Pool size=5;Pooling=true;Connection Timeout=6000;");
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            
        }
    }
	
	public class ContextTwo : DbContext
    {
        public DbSet<Post> Posts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder builder)
        {
            builder.UseSqlServer(@"Server=VT13-PC\SQLEXPRESS;Database=ContextTwo;User ID=sa;Password=1234;Max Pool Size=2000;Min Pool size=5;Pooling=true;Connection Timeout=6000;");
        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            
        }
    }
dnx . ef migration add -c ContextOne initial

dnx . ef migration apply -c ContextOne

dnx . ef migration add -c ContextTwo initial

dnx . ef migration apply -c ContextTwo

What happen if we want to join 2 tables from 2 databases?

var blog = new ContextOne().Blogs;
 var post = new ContextTwo().Posts;

 var query = from b in blog
 join p in post on p.Id equals p.BlogId
 select new { BlogUrl = b.Url, Title = p.Title };

 foreach (var b in query)
 {
 Console.Write(b);
 }
 Console.ReadLine();
Advertisements

One thought on “EntityFramework 7 Multi-Db

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s