Reputation: 97
Is it possible to get to the current connection from inside your code first "table" class?
I'm trying to write a MVC Multi Tenancy app (1 app, many db's) the easiest way i can think of is to pass the connection string (or tenant name) when creating the dbcontext (i've looked at other ways to do this, but don't really understand them). However once i go into the table class I cannot then access the current db connection to perform other actions i need.
Example code
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();
}
}
}
Upvotes: 1
Views: 223
Reputation: 4817
You don't have to make a constructor with a connection string parameter, you can create your dbcontext class like this:
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; }
}
And then call your connection context this way:
using (var conn = new ConnectionContext())
{
}
Upvotes: 0