We are attempting to use a repository pattern for an EF project. The user is allowed to select one of three separate (but structurally identical) databases to log on to (there is one for training, one for testing, and one for production).
We are currently using an EF 4 implementation and have generated our T4 via the ADO.Net EntityObject Generator. Our repository base class looks as follows:
public class RepositoryBase<C> : IDisposable
where C : ObjectContext, new()
{
private C _DataContext;
public virtual C DataContext
{
get
{
if (_DataContext == null)
{
_DataContext = new C();
}
return _DataContext;
}
}
//other code cut for brevity...
}
I think what we want is the ability to modify the “_DataConext = new C();” line so that it can use a connection string that is generated at runtime to point to the proper database. Unfortunately passing the connection string like this: _DataConext = new C(connectionString); is not allowed and results in this message: “Arguments cannot be passed to a ‘New’ used on a type parameter.”
I can see in the model.tt file’s code behind that there are three contructors: the default parameterless constructor, a constructor that has an EntityConnection parameter, and a third which has a connection string parameter (the one we want to use).
The question is how do we go about doing this? Any help is appreciated!
Well, problem is specifying a constructor with parameter on a generic type.. This is not allowed.
First solution would be to use reflection.
If you know what are the constructors defined:
A better solution would be to give the instance of C to the construtor of you repository.
Hope it helps