【问题标题】:Null Reference Exception when i use navigation property in model class当我在模型类中使用导航属性时出现空引用异常
【发布时间】:2013-12-02 13:28:46
【问题描述】:

我尝试在控制器操作中在数据库中添加新实体。
这是我的模型课

    public class Product
    {
    public int ProductID { get; set; }

    [Required(ErrorMessage = "Please enter product name")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter product model")]
    public string Model { get; set; }

    [Required(ErrorMessage = "Please enter product serial")]
    public string Serial { get; set; }

    [Required(ErrorMessage = "Please choose dealer")]      
    public int DealerID { get; set; }

    [Required]        
    public Guid ClientID { get; set; }

    [Required(ErrorMessage = "Please choose employee")]
    public Guid EmployeeID { get; set; }

    public virtual Dealer Dealer { get; set; }
    public virtual Client Client { get; set; }
    public virtual Employee Employee { get; set; }

    [DisplayName("Commercial use")]
    public bool UseType { get; set; }
}

这是在数据库中创建新产品的操作

    public ViewResult Create()
    {
        PopulateDropDownLists();
        var model = new Product();
        return View(model);
    }

    [HttpPost]
    public ActionResult Create(Product model)
    {
        try
        {
            if (ModelState.IsValid)
            {
                _repo.GetRepository<Product>().Add(model);
                _repo.Save();
                TempData["message"] = "Product was successfully created";
                return RedirectToAction("List");
            }
        }
        catch (DataException)
        {
            TempData["error"] =
                "Unable to save changes. Try again, and if the problem persists, see your system administrator.";
            return View("Error");
        }

        PopulateDropDownLists();
        return View("Create");
    }

CreateView 具有适当的模型类型(在这种情况下为产品类型)。代码如下

    @using System.Web.Mvc.Html
    @model STIHL.WebUI.Models.Product

    @using (Html.BeginForm())
    {
       @Html.EditorFor(m => m.Name)
       @Html.EditorFor(m => m.Model)
       @Html.EditorFor(m => m.Serial)

    <div class="form-group">
        @Html.LabelFor(m => m.DealerID, "Dealer")
        @Html.DropDownListFor(m => m.DealerID, new SelectList((IEnumerable)TempData["Dealers"],"DealerID", "DealerNumber"), string.Empty, new {@class = "form-control"})
        @Html.ValidationMessageFor(m => m.DealerID, null, new {@class = "help-block"})
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.EmployeeID, "Employee",new {@class = "control-label"})
        @Html.DropDownListFor(m => m.EmployeeID, new SelectList((IEnumerable)TempData["Employees"],"EmployeeID", "FullName"),string.Empty, new {@class="form-control"})
        @Html.ValidationMessageFor(m => m.EmployeeID, null, new {@class = "help-block"})       
    </div>

    <div class ="ok-cancel-group">
        <input class="btn btn-primary" type="submit" value="Create" />
        @Html.ActionLink("Cancel", "List","Product",new {@class = "btn btn-primary"})
    </div>
}                                   

我总是在 [HttpPost] 操作中得到空引用而不是模型,但是如果我使用 ViewModel 而不是 Model 一切都很好(下面的 ViewModel 代码)

public class ProductViewModel
{
    public Product Product { get; set; }
}

我认为它导致模型类具有虚拟属性,但无论如何我不明白为什么我使用 ViewModel 时可以。 谁能回答我? 提前谢谢。

【问题讨论】:

  • 我觉得你也应该把视图放上去!!
  • 如果从属性中删除“虚拟”会发生什么?
  • 如果我删除虚拟属性,我可以使用模型类,没有 ViewModel 也可以
  • 问题已编辑。我把查看代码放在那里

标签: c# asp.net-mvc entity-framework model asp.net-mvc-viewmodel


【解决方案1】:

virtual 属性不会改变结果。问题是视图被编写为绑定到视图模型,因此接受模型是行不通的。如果要使用模型;然后将视图绑定到模型。

【讨论】:

  • 当我使用模型类 ViewCreate 具有适当的类型(产品)。当我使用 ViewModel ViewCreate 有 ProductViewModel 类型。
猜你喜欢
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 2022-01-25
相关资源
最近更新 更多