将表连接结果传递给视图?

时间:2015-01-14 19:03:08

标签: c# asp.net-mvc razor

我有以下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会更方便。

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

1 个答案:

答案 0 :(得分:5)

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

尝试更改语句,以IEnumerable<Tuple<Models.Note, Models.Person>>创建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>