I have null ref ex when i try to get CAtegory my Product. i`m used Repository and UnitOfWork pattern. If you need more code - I can send. Presumably this is because the controller can't get a Category or CoverType object.
Shoppping cart Model: public class ShoppingCart { public int Id { get; set; }
public int ProductId { get; set; }
[ForeignKey("ProductId")]
[ValidateNever]
public Product Product { get; set; }
[Range(1, 1000, ErrorMessage = "Please enter a value between 1 and 1000")]
public int Count { get; set; }
//NEW
public decimal FactTime { get; set; }
public string ApplicationUserId { get; set; }
[ForeignKey("ApplicationUserId")]
[ValidateNever]
public ApplicationUser ApplicationUser { get; set; }
[NotMapped]
public double Price { get; set; }
}
CartController:
public IActionResult Index()
{
var claimsIdentity = (ClaimsIdentity)User.Identity;
var claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);
ShoppingCartVM = new ShoppingCartVM()
{
ListCart = _unitOfWork.ShoppingCart.GetAll(u => u.ApplicationUserId == claim.Value,
includeProperties: "Product"),
OrderHeader = new()
};
foreach(var cart in ShoppingCartVM.ListCart)
{
cart.Price = GetPriceBasedOnQuantity(cart.Count, cart.Product.Price);
ShoppingCartVM.OrderHeader.OrderTotal += (cart.Price * cart.Count);
}
return View(ShoppingCartVM);
}
Product Model:
public int Id { get; set; }
[Required]
[Display(Name = "Task Type")]
public int TaskTypeId { get; set; }
[ValidateNever]
public TaskType TaskType { get; set; }
public string? Description { get; set; }
[Required]
public string? Author { get; set; }
[Required]
[Range(1, 10000)]
[Display(Name = "Price")]
public decimal Price { get; set; }
[Required]
public decimal? OrientedTime { get; set; }
[ValidateNever]
public string? ImageUrl { get; set; }
[Required]
[Display(Name = "Category")]
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
[ValidateNever]
public Category Category { get; set; }
[Required]
[Display(Name ="Cover Type")]
public int? CoverTypeId { get; set; }
[ValidateNever]
public CoverType CoverType { get; set; }
}
Repository GetAll Model:
public IEnumerable<T> GetAll(Expression<Func<T, bool>>? filter=null, string? includeProperties = null)
{
IQueryable<T> query = dbSet;
if (filter != null)
{
query = query.Where(filter);
}
if (includeProperties != null)
{
foreach(var includeProp in includeProperties.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries))
{
query = query.Include(includeProp);
}
}
return query.ToList();
}