EF6:如何在列表中搜索项目?

EF6: How do I search for an item in a List?

我有一个简单的 ASP.Net MVC 应用程序 Entity Framework 6.

我有两个 table:一个 "Contacts" 列表(包含姓名、地址和 phone#s)和第二个 table 记录零个或多个 "Notes" 每个联系人的历史记录:

Models/Contact.cs:

   public class Contact
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ContactId { get; set; }
        public string Name { get; set; }
        public string EMail { get; set; }
        public string Phone1 { get; set; }
        ...
        public virtual List<Note> Notes { get; set; }
    }

Models/Note.cs:

public class Note
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int NoteId { get; set; }
    public string Text { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime? Date { get; set; }
    [ForeignKey("Contact")]
    public int ContactId { get; set; }
    public virtual Contact Contact { get; set; }
}

我在 Visual Studio 中做了一个 "Add Controller",它自动生成了 "ContactsController.cs" 和 "Index.cshtml"、"Details.cshtml"、"Edit.cshtml" 和 "ContactsController.cs" 的视图"Delete.cshtml"。所有自动生成的代码看起来都不错,并且运行良好。但是它没有显示任何 "Notes".

我能够显示 "notes" 并通过将以下内容添加到 "Details.cshtml" 和 "Edit.cshtml" 来添加编辑或删除笔记的链接:

Views/Contacts/Edit.cshtml:

@model ContactsApp.Models.Contact
...
<h4>Notes</h4>
<table class="table">
    <tr>
        <th>Date</th>
        <th>Note</th>
        <th>&nbsp;</th>
    </tr>

    @for (int i = 0; i < Model.Notes.Count(); i++)
    {
        <tr>
            <td>@Html.DisplayFor(model => model.Notes[i].Date)</td>
            <td>@Html.DisplayFor(model => model.Notes[i].Text)</td>
            <td>
                @Html.ActionLink("Edit Note", "EditNote", new { noteId = Model.Notes[i].NoteId }) |
                @Html.ActionLink("Delete Note", "DeleteNote", new { noteId = Model.Notes[i].NoteId })
            </td>
        </tr>
    }
</table>

我还创建了一个 "EditNote.cshtml" 视图...但我一直无法弄清楚如何从 ContactsController 中调用它:

Controllers/ContactsController.cs:

   // GET: Contacts/EditNote?noteId=3
    public async Task<ActionResult> EditNote(int? noteId)
    {
        if (noteId == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Note note = await db.Contacts.Where(c => c.Notes.noteId == noteId);
        if (note == null)
        {
            return HttpNotFound();
        }
        return View(note);
    }

问:获取 "Note" 并将其传递给 "EditNote" 视图的正确 ASP.Net MV 语法是什么?

由于以下行,您的代码不应该正常编译:

Note note = await db.Contacts.Where(c => c.Notes.noteId == noteId);

右边表达式的类型是IEnumerable<Contact>,而你赋给它的变量类型是Note。这应该更改为以下内容:

Note note = await db.Notes.FirstOrDefaultAsync(note => note.NodeId == noteId);

顺便说一句:Where 是一个同步调用,所以不需要使用 await 关键字。

您正在返回联系人。

您应该查询注释并使用 FirstOrDefault。

db.Notes.Where(n=> n.NoteId =id).FirstOrDefault();

如果您想 select 通过 id 和注释 id 从联系人中获取更高效率,请尝试 Using LINQ, select list of objects inside another list of objects