将 table 个联接结果传递给视图?

Passing table join results to a view?

我有以下 ASP.Net MVC 控制器操作,它连接了 2 个表:-

public ActionResult PersonNotes()
{
    var model = db.Notes
        .Join(db.People, p => p.NotesListId, n => n.NotesListId, 
            ((note, person) => new { note, person })).ToList();
    return View(model);
}

在我看来,我有以下模型声明:-

@model IEnumerable<Tuple<Models.Note, Models.Person>>

我收到以下错误:-

System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousTypef`2[Models.Note,Models.Person]]', but this dictionary requires a model item of type System.Collections.Generic.IEnumerable`1[System.Tuple`2[Models.Note,Models.Person]]'.

我意识到我可以在连接中使用 ViewModel 和 Select(),但如果无需创建 ViewModel 就可以访问所有项目会方便得多。

在我看来什么是正确的声明,或者我试图通过这种方式无法实现的目标是什么?

您正在返回一个匿名对象,您的视图需要一个带有 Tuple 的模型。 The anonymous type is generated by the compiler and is not available at the source code level.

尝试更改您的语句以创建 IEnumerable<Tuple<Models.Note, Models.Person>> with Tuple.Create:

var model = db.Notes
    .Join(db.People, p => p.NotesListId, n => n.NotesListId, 
        ((note, person) => Tuple.Create(note, person))).ToList();

Tuple.Create

如果您正在使用 Linq to Entities 或 Entity Framework,那么您将需要将 IQueryable 迭代到 Tuple 或使用 class.

var model = db.Notes
    .Join(db.People, p => p.NotesListId, n => n.NotesListId, 
        ((note, person) => new { note, person }))
    .AsEnumerable()
    .Select(x => Tuple.Create(x.note, x.person))
    .ToList();

创建一个 class 来保存 PersonNote

public class PersonNote
{
    public Person Person { get; set; }
    public Note Note { get; set; }
}

更改语句以使用新的 PersonNote

var model = db.Notes
    .Join(db.People, p => p.NotesListId, n => n.NotesListId, 
        ((note, person) => new PersonNote { Note = note, Person = person }))
    .ToList();

更换模型。

@model IEnumerable<PersonNote>