c# - 当我在模型类中使用导航属性时出现空引用异常

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

我尝试在 Controller 操作中的数据库中添加新实体。
这是我的模型类

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

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

    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 时它没问题。 谁能回答我? 提前致谢。

最佳答案

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

关于c# - 当我在模型类中使用导航属性时出现空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20329501/

相关文章:

c# - 从 WinDev 调用 DLL 方法

c# - 在 Azure 门户中跟踪 System.Diagnostics.Trace 日志

c# - 创建自动打开的文档

c# - 在关注点之间传递变量的正确方法

c# - 在 Entity Framework 中使用 Postgis 的几何类型

.net - 如何查看实体集和未提交的更改?

c# - 为什么此 AsParallel 操作会抛出数据提供程序错误?

c# - Win32.DestroyIcon 与 Icon.Dispose

asp.net-mvc - 如何在单个API调用中使用不同的指标检查Elasticsearch的运行状况?

c# - WebApi 自定义授权属性不起作用