【问题标题】:How to connect Azure federated root database and apply federation in entity framework DBContext?如何连接 Azure 联合根数据库并在实体框架 DBContext 中应用联合?
【发布时间】:2013-09-24 19:03:58
【问题描述】:

我正在使用 Asp.Net web api、实体框架和 SQL Azure。在我的解决方案中,我有从数据库生成的 .edmx 文件。以下代码行上下文实体。

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; }
}

这是多租户应用程序,基于用户登录,我需要连接到具有特定 shardId(federation id) 的数据库。

private Entities _db = new Entities();

在为 dbcontext 创建实例时,我想基于 Shardid 建立新的连接。

【问题讨论】:

    标签: c# entity-framework azure ef-code-first azure-sql-database


    【解决方案1】:

    花了太多时间后,我想通了。它对我来说很好。

     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;
    

    必须将EntityDatabase连接转换为SqlConnection,正常执行federation命令。

    实体将针对指定的 shardId 执行查询,连接到正确的数据库。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多