I need to be able to call the Entity Framework model constructor of my model in 2 different ways. I either pass a connection string to my class, let's call it MyDbConnection
, or I pass an existing EntityConnection
(DBConnection
) to my context, which comes from another application.
Everything is fine and works so far.
The problem I have, is: every time I want to use this custom way of opening my context in a new project, I need to define the 2 constructors in MyDbConnection
which is quite a hassle.
Like this:
public partial class MyEntityConnection : DbContext
{
public MyEntityConnection(string con) : base(con)
{
}
public MyEntityConnection(DbConnection con, bool contextOwnsConnection) : base(con, contextOwnsConnection)
{
}
}
Then in my own implementation I do something like this (for the string overload):
public T GetDbContext() => (T)Activator.CreateInstance(typeof(T), _connectionstring);
and here is the problem. If I forgot to create one or both constructors, this would throw an exception.
Now I do know that you can modify the EF template to autogenerate those constructors, but im Looking for a Hands-Off Way to Archive this.
Some Way to Create the Instance of my Derived Class with a Constructor, that does not exist, and that Construtor should call its Base Constructor.
If there is a better Way to Archive this, im all ears.
private T GetExistingDbContext()
{
try
{
EntityConnection econ = new EntityConnection(_internalMetadataWorkspace, _internalExistingSqlConnection);
return (T)Activator.CreateInstance(typeof(T), econ, false);
}
catch (MissingMethodException)
{
}
catch (Exception catr)
{
Console.WriteLine(catr);
throw;
}
}
edit: fixed the Formating..Good God...First time Posting, sorry
Aucun commentaire:
Enregistrer un commentaire