Reputation: 687
I have implemented a simple generic repository for my asp.net web api project following this easy to follow guide :
http://www.dataworks.ie/blog/entity_framework_5_with_automapper_and_repository_pattern
That works fine.
However my solution in development has two simple databases with the same schema - a SQL Server CE for test/dev and when running local (and offline) and a SQL Azure when online. Both have EF layers created in separate assemblies. I switch the DbContext
via the web.config
connection string in the constructor of the context class. The problem is with my controller code.
For e.g. if using Azure I would have
public ActionResult Index()
{
IGenericRepository<MyProj.Data.SqlAzure.User> userRepo = new GenericRepository<MyProj.Data.SqlAzure.User>();
if I'm using SQL Server CE, I would have
public ActionResult Index()
{
IGenericRepository<MyProj.Data.SqlCe.User> userRepo = new GenericRepository<MyProj.Data.SqlCe.User>();
So I have to manually change to the correct assembly namespace to reference my entities when I switch databases.
Sorry if this has been done to death as haven't done one of these in awhile but what is the best/elegant solution for this scenario? The above one is very dirty looking. Also all my generic repository code is currently in a model folder in same namespace as the web app.
Upvotes: 1
Views: 1446
Reputation: 256
The only solution that springs to mind is to have a factory class to create the instances with a switch defined in the config file, e.g.
public DbRepositoryFactory
{
public IGenericRepository<User> GetUserRepository()
{
return ConfigurationManager.AppSettings["DbSwitch"].Equals("Azure")
? new GenericRepository<MyProj.Data.SqlAzure.User>()
: new GenericRepository<MyProj.Data.SqlCe.User>()
}
}
Either that or to use reflection.
Upvotes: 1
Reputation: 18387
Since you're using generic repository, it won't know how to determine which user entity you want unless you tell it.
What you can do, create a factory that solves it for you. GenericRepositorySqlAzure and GenericRepositorySqlCe
Upvotes: 1