1

这是设置:

模型:

public class Device
{
    [Key]
    public int Id { get; set; }
    [MaxLength(50)]
    public String Name { get; set; }
    public Category Category { get; set; }
    public Manufactor Manufactor { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<Status> Status { get; set; }
}

控制器动作:

public ActionResult Index()
{
   var devices = db.Devices.Include("Categories").Include("Manufactors").Select(x => new Device
                   {
                        Name = x.Name,
                        Category = x.Category,
                        Comments = x.Comments,
                        Manufactor = x.Manufactor,
                        Status = x.Status
                    });
    return View(db.Devices.ToList());
}

看法:

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Manufactor.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Category.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Status)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

这里的问题是,只显示名称,但item.Category不显示item.Manufactor。如果我将行更改为简单的 @item.Category.Name 我将遇到 Nullreference 异常。

在我的数据库中查看设备表,列出了 2 个设备,每个设备中都有 CategoryId 和 ManufactorId。

我认为这是 20 分钟的明智之举,但似乎我在某处犯了严重错误。请帮我解决这个错误。

如果您需要其他代码,只需将其发布在评论中。

亲切的问候

编辑: 针对那些非常有用的答案:错误是我的控制器操作错误。该解决方案有效:

return View(db.Devices.Include(d => d.Manufactor).Include(d => d.Category).ToList());
4

2 回答 2

4

Your model property is called Category, not Categories, so make sure you are making the proper Include:

db.Devices.Include("Category")...

Same stands true for the Manufacturers of course. Your model property's called Manufactor and not Manufactors so include the correct one:

.Include("Manufactor")

Now EF will make proper joins in the tables and hydrate your Category and Manufactor properties that you could use in your view.

于 2013-10-17T19:59:14.087 回答
3

In addition to Darin's answer: there is also a strong-typed variant of the Include() method available which will warn you at compile-time when you use non-existing properties:

db.Devices.Include(d => d.Category)

Reference: DbExtensions.Include()

于 2013-10-17T20:08:15.077 回答