【问题标题】:"Value cannot be null. Parameter name: source" while add item from connected table in View“值不能为空。参数名称:源”同时从视图中的连接表添加项目
【发布时间】:2020-05-30 11:49:33
【问题描述】:

在我的项目中,我有两个表: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; }

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; }

调用的部分视图

@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

   ...
}

控制器

public IActionResult Index()
  {
     ViewBag.RestaurantWidget=
        (
           from restaurant in _context.Restaurant
           select restaurant 
           ).Take(5).ToList();
        return View();
  }

其他信息:每家餐厅至少有一个评分。没有一家餐厅不会有任何评分

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-core


    【解决方案1】:

    我在 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();
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 2019-11-06
      • 2018-08-22
      • 1970-01-01
      相关资源
      最近更新 更多