I am facing an issue while implementing the Repository Pattern [UoW] for MVC4 with EF6.
Error: 'XX.DataAccess.Context' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TContext' in the generic type or method 'XX.DataAccess.WriteRepository'
//Data Access layer Class for Saving/Deleting/Retriving etc. Inherits WriteRepository
public class Common : WriteRepository<Context>, ICommon
{
//Method
}
//Repository Pattern
public abstract class WriteRepository<TContext> : IWriteRepository where TContext : DbContext, new()
{
private readonly TContext _context;
protected TContext Context { get { return _context; } }
protected WriteRepository()
{
_context = new TContext();
}
//Save Method
//Delete Method
//Retrive Method
//Find Method
}
//DB Context Class //Here i need to build dynamic connection string which takes the Client ID as the Parameter. If i use it in the parameter it gives me the error for Data Access method implementations which is mentioned above.
public partial class Context : DbContext
{
static Context ()
{
Database.SetInitializer<Context>(null);
}
public Context (int ClientID = 0)
: base(ConnectionString(ClientID))
{
var objContext = (this as IObjectContextAdapter).ObjectContext;
objContext.CommandTimeout = 180;
}
//DBSet's
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Mapping
}
private static string ConnectionString(int ClientID = 0)
{
//return connection string
}
}
Let me know what changes do i need to make it work.
The problem is the
new()
constraint onWriteRepository
. The constraint cannot be satisfied becauseContext
does not have an zero-argument constructor, since you need to pass theClientID
in when you create it. Therefore, remove thenew()
constraint, and instead modify theWriteRepository
constructor to take an argument of typeTContext
:Then, in the derived class, create the
Context
and pass it in as an argument to the base constructor.Of course, any other classes that already derive from
WriteRepository
will need to be modified as well. I hope this helps!