我正在编写一个MVC 5互联网应用程序,并且在初始化Lazy对象时遇到了一些麻烦。延迟初始化 - 无效参数
这里是我的代码:
public Lazy<IGenericRepository<Account>> accounts;
public IGenericRepository<Account> accountsNotLazy;
我想在构造函数中调用类初始化这两个变量。
这是构造函数代码;
public GenericMultipleRepository(DbContext dbContext)
{
this.dbContext = dbContext;
accounts = new Lazy<GenericRepository<Account>>(dbContext);
accountsNotLazy = new GenericRepository<Account>(dbContext);
}
我可以请这个代码帮忙吗?
在此先感谢。
编辑
我想完全相同的初始化的变量accountsNotLazy
,但使用Lazy loading
。变量accountsNotLazy
正确初始化,accounts
怎么没有?唯一的区别是Lazy
关键字。
这些都是错误:
The best overloaded method match for 'System.Lazy>.Lazy(System.Func>)' has some invalid arguments
除了:
cannot convert from 'System.Data.Entity.DbContext' to 'System.Func>'
这里是GenericRepository类:
public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
protected DbSet<TEntity> DbSet;
private readonly DbContext _dbContext;
public GenericRepository(DbContext dbContext)
{
_dbContext = dbContext;
DbSet = _dbContext.Set<TEntity>();
}
public GenericRepository()
{
}
public IQueryable<TEntity> GetAll()
{
return DbSet;
}
public async Task<TEntity> GetByIdAsync(int id)
{
return await DbSet.FindAsync(id);
}
public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return DbSet.Where(predicate);
}
public async Task EditAsync(TEntity entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
}
public async Task InsertAsync(TEntity entity)
{
DbSet.Add(entity);
await _dbContext.SaveChangesAsync();
}
public async Task DeleteAsync(TEntity entity)
{
DbSet.Remove(entity);
await _dbContext.SaveChangesAsync();
}
}
很确定你不能传递'dbContext'到类似的构造函数中。它需要'Func' –
DavidG
代码无法如图所示进行编译 - 所以这段代码没有办法使运行时“参数超出范围”异常。请检查帖子中的代码是否是您遇到问题的代码。 –