in my project i have Two table: Restaurant(RestaurantId, Name, ...., Adress) and RestaurantReviews(ReviewsId, Mark, ...., RestaurantId). In my PartialView i try show Restaurant info and calculate Average Mark, but if i try calculate Average i getting error:
ArgumentNullException: Value cannot be null. (Parameter 'source')
RestaurantModel
public class Restaurant
{
[Key]
public int RestaurantId{ get; set; }
....
[Required(ErrorMessage = "Restaurant name is empty")]
public string Name{ get; set; }
....
public virtual ICollection<RestaurantReviews> RestaurantReviews{ get; set; }
RestaurantReviewsModel
public class RestaurantReviews
{
[Key]
public int RestaurantReviewsId { get; set; }
....
[Required(ErrorMessage = "Restaurant mark is empty")]
public int Mark{ get; set; }
[ForeignKey("Restaurant")]
public int RestaurantId { get; set; }
public virtual Restaurant Restaurant {get; set; }
DbContext
public DbSet<Restaurant> Restaurant { get; set; }
public DbSet<RestaurantReviews> RestaurantReviews{ get; set; }
Called PartialViews
@await Html.PartialAsync("~/Views/Restaurant/RestaurantWidget.cshtml", (IEnumerable<Firma.Data.Data.CMS.Restaurant>)ViewBag.RestaurantWidget)
RestaurantWidget.cshtml
@model IEnumerable<Firma.Data.Data.CMS.Restaurant>
@foreach (var item in Model)
{
...
@item.Name
...
//Without this line everything is ok
@item.RestaurantReviews.Average(x=>x.Mark)
//Without this line everything is ok
...
}
Controller
public IActionResult Index()
{
ViewBag.RestaurantWidget=
(
from restaurant in _context.Restaurant
select restaurant
).Take(5).ToList();
return View();
}
Additional info: Each restaurant has at least one rating. There is no restaurant that would not have any rating
I find answer to my question, in Controller i change
public IActionResult Index()
{
ViewBag.RestaurantWidget=
(
from restaurant in _context.Restaurant
select restaurant
).Take(5).ToList();
return View();
}
to code below
ViewBag.RestaurantWidget= _context.Restaurant.Include(p=>p.RestaurantReviews).Take(4).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.