C
C#15mo ago
EliasGPS

✅ Working with repository in ASP.NET

I'm trying to use an orderRepository. But when i use it i get the message in my index.cshtml file: System.NullReferenceException: 'Object reference not set to an instance of an object.'
9 Replies
EliasGPS
EliasGPS15mo ago
Now in my OrderController i have a method Index that looks like this:
public IActionResult Index()
{
/*var orders = _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product).ToList();*/
var orders = orderRepository.All();
return View(orders);
}
public IActionResult Index()
{
/*var orders = _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product).ToList();*/
var orders = orderRepository.All();
return View(orders);
}
the orders variable that is in comment works. But my repo not. The All method looks like follows:
public override IEnumerable<Order> All()
{
return _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product)
.ToList();
}
public override IEnumerable<Order> All()
{
return _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product)
.ToList();
}
so basically when i use this code in my Index:
/*var orders = _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product).ToList();*/
/*var orders = _context.Orders
.Include(order => order.Orderlines)
.ThenInclude(orderline => orderline.Product).ToList();*/
everything works but i want to use the repo
jalepi
jalepi15mo ago
it seems you are missing registering that dependency. dependency injection registrations are typically done inside Program.cs by services.AddSingleton, or AddTransient or AddScoped
EliasGPS
EliasGPS15mo ago
yeah yeah i think i found something but i reagisterd it
EliasGPS
EliasGPS15mo ago
EliasGPS
EliasGPS15mo ago
but i think the issue is in my OrderController i do it like this:
EliasGPS
EliasGPS15mo ago
EliasGPS
EliasGPS15mo ago
so i'm calling the GenericRepository instead of the Orderrepository yeah i found it if i use this code in my OrderController is works:
EliasGPS
EliasGPS15mo ago
jalepi
jalepi15mo ago
nice, congrats!