我正在跟随一位讲师,在将产品添加到他制作的应用程序的购物车时,我遇到了这样的错误,当我检查我的服务层和Repo层时,我没有发现问题,你能分享你的解决方案建议吗?
我在你的警告下删除了图片,我得到的错误如下
处理请求时发生未处理的异常。
“异常:找不到产品!
ProductService.cs中的Services.Abstracts.ProductService.GetOneProduct(int id,bool trackChanges),第48行“
IProductService层
public interface IProductService
{
IEnumerable<Product> GetAllProducts(bool trackChanges);
Product? GetOneProduct(int id,bool trackChanges);
void CreateProduct(ProductDtoForInsertion productDto);
void UpdateOneProduct(ProductDtoForUpdate productDto);
void DeleteOneProduct(int id);
ProductDtoForUpdate GetOneProductForUpdate(int id, bool trackChanges);
}
ProductService层
public Product? GetOneProduct(int id, bool trackChanges)
{
var product = _manager.Product.GetOneProduct(id, trackChanges);
if (product is null)
throw new Exception("Product not found!");
return product;
}
IProductRepository层
public interface IProductRepository :IRepositoryBase<Product>
{
IQueryable<Product> GetAllProducts(bool trackChanges);
Product? GetOneProduct(int id ,bool trackChanges);
void CreateOneProduct(Product product);
void DeleteOneProduct(Product product);
void UpdateOneProduct(Product entity);
}
ProductRepository层
public Product? GetOneProduct(int id, bool trackChanges)
{
return FindByCondition(p=>p.Id.Equals(id),trackChanges);
}
Cart.cshtml.cs层
public IActionResult OnPost(int productId,string returnUrl)
{
Product ? product =_manager
.ProductService
.GetOneProduct(productId,false);
if (product is not null)
{
Cart.AddItem(product,1);
}
return Page();
}
我试着写我使用的所有图层,如果有一个图层你认为缺失或你想看,请指定
我重新组织了层,并将其与GitHub上教程共享的项目进行了比较,但我找不到解决方案
我有可用的回购层,我将在下面添加它们
public interface IRepositoryBase<T>
{
IQueryable<T> FindAll(bool trackChanges);
T? FindByCondition(Expression<Func<T, bool>> expression, bool trackChanges);
void Create(T entity);
void Remove(T entity);
void Update(T entity);
}
public T? FindByCondition(Expression<Func<T, bool>> expression, bool trackChanges)
{
return trackChanges
? _context.Set<T>().Where(expression).SingleOrDefault()
:_context.Set<T>().Where(expression).AsNoTracking().SingleOrDefault();
}