Ramesh Bolla
Ramesh Bolla

Reputation: 412

How to connect Azure federated root database and apply federation in entity framework DBContext?

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.

Upvotes: 0

Views: 363

Answers (1)

Ramesh Bolla
Ramesh Bolla

Reputation: 412

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;
                    connection.Open();
                    var command = new SqlCommand();                
                    string federationCmdText = @"USE FEDERATION Customer_Federation(ShardId =" + shardId + ") WITH RESET, FILTERING=ON";
                    command.Connection = connection;
                    command.CommandText = federationCmdText;
                    command.ExecuteNonQuery();
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.

Upvotes: 2

Related Questions