Reputation: 441
why this error occur with .net mvc razor view
Controller Code
ViewBag.LowStock = db.StockInformations.Where(x => x.Qty <= x.MinStockLevel);
View Code
@{
List<StockInformation> DangerLavel = (List<StockInformation>)ViewBag.LowStock;
var count = 0;
ViewBag.Title = "Create";
}
Upvotes: 2
Views: 52
Reputation: 121
The error occurs because you are storing a DbQuery<StockInformation> and trying to get a List<StockInformation>.
The code below returns a DbQuery<StockInformation>.
db.StockInformations.Where(x => x.Qty <= x.MinStockLevel)
To fix it just call the ToList method:
db.StockInformations.Where(x => x.Qty <= x.MinStockLevel).ToList();
The ToList method will create a List based on the DbQuery returned from the Where method.
Upvotes: 2
Reputation: 726799
Since LowStock
is a query, you cannot cast it to List<StockInformation>
. Instead, you should call ToList()
to it:
List<StockInformation> DangerLavel = ViewBag.LowStock.ToList();
The call retrieves the data from DbQuery
after applying the filter, producing a list in memory.
Upvotes: 3