我在使用EF6为MVC4实现存储库模式[UoW]时遇到了问题。
错误:'XX.DataAccess.Context'必须是具有公共无参数构造函数的非抽象类型,才能在泛型类型或方法'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 //这里我需要构建动态连接字符串,它将客户端ID作为参数。如果我在参数中使用它,它会给我上面提到的数据访问方法实现的错误。
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
}
}
让我知道我需要做些什么改变才能让它发挥作用。
答案 0 :(得分:3)
问题是new()
上的WriteRepository
约束。无法满足约束,因为Context
没有零参数构造函数,因为您需要在创建它时传递ClientID
。因此,请删除new()
约束,而是修改WriteRepository
构造函数以采用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
}
然后,在派生类中,创建Context
并将其作为参数传递给基础构造函数。
//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))
{
}
}
当然,任何其他已经从WriteRepository
派生的类也需要进行修改。我希望这有帮助!