1

是否可以从代码第一个“表”类中访问当前连接?

我正在尝试编写一个 MVC 多租户应用程序(1 个应用程序,许多 db)我能想到的最简单的方法是在创建 dbcontext 时传递连接字符串(或租户名称)(我已经查看了其他方法这个,但并不真正理解它们)。但是,一旦我进入表类,我就无法访问当前的数据库连接来执行我需要的其他操作。

示例代码

public class ConnectionContext : DbContext
{
    public ConnectionContext(String connectionString) 
        : base(connectionString)
    {
        if (!this.Database.Exists())
            throw new Exception("Database does not exist");
    }

    public DbSet<Table1> Table1 { get; set; }
}

[Table("Table1")]
public class Table1
{
    [Key]
    public String Column1 { get; set; }

    public String Column2 { get; set; }

    public Int32 GetNoOfColumns()
    {
        using (var conn = new ConnectionContext("???")) // <-- **issue here**
        {
            //Code to get info

            return 0;
        }
    }

    public void Authorize()
    {
        using (var conn = new ConnectionContext("???")) // <-- **issue here**
        {
            this.Column2 = "Authorized";

            conn.Entry(this).State = EntityState.Modified;
            conn.SaveChanges();
        }
    }
}
4

2 回答 2

1

不确定这是否可能以我正在查看的方式进行。

于 2012-10-08T11:12:04.167 回答
0

您不必使用连接字符串参数创建构造函数,您可以像这样创建 dbcontext 类:

public class ConnectionContext : DbContext
{
    public ConnectionContext() 
        : base("nameOrConnectionString")
    {
        if (!this.Database.Exists())
            throw new Exception("Database does not exist");
    }

    public DbSet<Table1> Table1 { get; set; }
}

然后以这种方式调用您的连接上下文:

using (var conn = new ConnectionContext())
{
}
于 2012-08-30T11:12:54.117 回答