【发布时间】:2023-03-20 02:14:01
【问题描述】:
我的代码有问题。我需要帮助。
我的代码是 (new EFProductRepository()) 的基础,并表示它不包含采用 0 个参数的构造函数。
这是我的 ProductController 类:
public class ProductController : ApiController
{
private readonly IRepository<Product> _repository;
public ProductController()
: this(new EFProductRepository<Product>())
{ }
public ProductController(IRepository<Product> repository)
{
_repository = repository;
}
public IEnumerable<Product> Get()
{
return _repository.Get;
}
EFProductRepository 类:
public class EFProductRepository<T>: IRepository<T> where T: Entity
{
readonly EFDbContext _context;
public EFProductRepository(EFDbContext context)
{
_context = context;
}
public IQueryable<T> Get
{
get { return _context.Set<T>();}
}
public IQueryable<T> GetIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _context.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public T Find(object[] keyValues)
{
return _context.Set<T>().Find(keyValues);
}
public void Add(T entity)
{
_context.Set<T>().Add(entity);
}
public void Update(T entity)
{
var entry = _context.Entry(entity);
if (entry.State == EntityState.Detached)
{
_context.Set<T>().Attach(entity);
entry = _context.Entry(entity);
}
entry.State = EntityState.Modified;
}
public void AddOrUpdate(T entity)
{
//uses DbContextExtensions to check value of primary key
_context.AddOrUpdate(entity);
}
public void Delete(object[] keyValues)
{
//uses DbContextExtensions to attach a stub (or the actual entity if loaded)
var stub = _context.Load<T>(keyValues);
_context.Set<T>().Remove(stub);
}
}
IRepository 接口:
public interface IRepository<T> where T : Entity
{
IQueryable<T> Get { get; }
IQueryable<T> GetIncluding(params Expression<Func<T, object>>[] includeProperties);
T Find(object[] keyValues);
void Add(T entity);
void Update(T entity);
void AddOrUpdate(T entity);
void Delete(object[] keyValues);
}
以及产品和实体类:
public class Product : Entity
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public string Category { get; set; }
}
public class Entity
{
public int Id { get; set; }
}
【问题讨论】:
-
你需要将
EFDbContext的实例传递给EFProductRepository的构造函数。
标签: c# asp.net-mvc repository