Repository Pattern with Entity Framework and MVC4

2019-08-10 22:27发布

问题:

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.

回答1:

The problem is the new() constraint on WriteRepository. The constraint cannot be satisfied because Context does not have an zero-argument constructor, since you need to pass the ClientID in when you create it. Therefore, remove the new() constraint, and instead modify the WriteRepository constructor to take an argument of type TContext:

//Repository Pattern
public abstract class WriteRepository<TContext> : IWriteRepository where TContext : DbContext
{
    private readonly TContext _context;

    protected TContext Context { get { return _context; } }

    protected WriteRepository(TContext context)
    {
        _context = context;
    }

    //Save Method

    //Delete Method

    //Retrive Method

    //Find Method

}

Then, in the derived class, create the Context and pass it in as an argument to the base constructor.

//Data Access layer Class for Saving/Deleting/Retriving etc. Inherits WriteRepository
public class Common : WriteRepository<Context>, ICommon
{
    public Common(int clientID)
        :base(new Context(clientID))
    {

    }
}

Of course, any other classes that already derive from WriteRepository will need to be modified as well. I hope this helps!