I am creating an application which uses Entity Framework; specifically, Database First.
When the user logs in, a ConnectionString
is created at run-time which is then intended to be used for any data handling in the application.
I have already found a number of solutions to this on the Internet which suggest that the way to do this is to implement another constructor for the DbContext
class which is created which calls the base DbContext(string)
:
public ApplicationDbContext(SqlConnection Connection)
: base(Connection.ConnectionString)
{
}
This, I have created in a separate file which is a public partial class
of the generated code, to account for any further generated code overwriting what's already in those files.
However, when the application is running, as soon as an ApplicationDbContext
is created using this additional constructor, the following exception is raised:
"The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development..."
This would make sense as I'm using a Database first approach. However, all of the answers I have seen where Database First is used suggest doing this.
Having looked into it a little further on MSDN, I see that there is actually another DbContext
constructor that I could use: DbContext(String, DbCompiledModel)
. I am wondering whether this is what I am missing and this is the constructor I need, since I would have said I am using a compiled model (...or am I?).
However, is this the correct way to approach it or does this need to be handled another way?