![](/img/trans.png)
[英]Value cannot be null. Parameter name: source
[英]“Value cannot be null. Parameter name: source” while add item from connected table in View
在我的項目中,我有兩個表:Restaurant(RestaurantId, Name, ...., Adress) 和 RestaurantReviews(ReviewsId, Mark, ...., RestaurantId)。 在我的 PartialView 中,我嘗試顯示餐廳信息並計算平均分數,但如果我嘗試計算平均值,則會出現錯誤:
ArgumentNullException: Value cannot be null. (Parameter 'source')
餐廳模特
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; }
餐廳評論模型
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; }
數據庫上下文
public DbSet<Restaurant> Restaurant { get; set; }
public DbSet<RestaurantReviews> RestaurantReviews{ get; set; }
稱為部分視圖
@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();
}
附加信息:每家餐廳至少有一個評級。 沒有一家餐廳不會有任何評分
我找到了我的問題的答案,在Controller我改變
public IActionResult Index()
{
ViewBag.RestaurantWidget=
(
from restaurant in _context.Restaurant
select restaurant
).Take(5).ToList();
return View();
}
在下面編碼
ViewBag.RestaurantWidget= _context.Restaurant.Include(p=>p.RestaurantReviews).Take(4).ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.