Take the 2-minute tour ×

I am working with Asp.Net web api, entity framework & SQL Azure. In my solution solution i have .edmx file generated from database. following code lines context Entities.

public partial class Entities : DbContext     
    public Entities(): base("name=Entities")
    {         }             
    protected override void OnModelCreating(DbModelBuilder modelBuilder)         
    {             throw new UnintentionalCodeFirstException();         }            
    public DbSet<Activity> Activities { get; set; }

This is multi-tenant application, based on user login i need to connect to database with specific shardId(federation id).

private Entities _db = new Entities();

On creating instance to dbcontext, i would like to establish new connection based on Shardid.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

After spending too much time, i figured it. Its works fine to me.

 var   customerEntity = new Entities(ConnectionStringCustomerDB());
                    var connection = new SqlConnection();
                    connection =(SqlConnection) customerEntity.Database.Connection;
                    var command = new SqlCommand();                
                    string federationCmdText = @"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";
                    command.Connection = connection;
                    command.CommandText = federationCmdText;
return Entities;

Have to convert EntityDatabase connection to SqlConnection, execute federation command as normal way.

Entities will execute queries against specified shardId, connects to right database.

share|improve this answer

Your Answer


