tr3*_*r3v 0 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);
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我有以下模型声明: -
@model IEnumerable<Tuple<Models.Note, Models.Person>>
Run Code Online (Sandbox Code Playgroud)
我收到以下错误: -
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]]'.
Run Code Online (Sandbox Code Playgroud)
我意识到我可以在我的连接中使用ViewModel和Select(),但只需访问所有项目而不必创建ViewModel会更方便.
在我看来,正确的声明是什么,或者我试图通过这种方式实现的是什么?
您正在返回一个匿名对象,您的视图需要一个带有的模型Tuple.匿名类型由编译器生成,在源代码级别不可用.
试着改变你的语句来创建一个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();
Run Code Online (Sandbox Code Playgroud)
如果您使用Linq to Entities或Entity Framework,那么您将需要迭代IQueryable到a Tuple或使用a 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();
Run Code Online (Sandbox Code Playgroud)
要么
创建一个class以保持Person和Note.
public class PersonNote
{
public Person Person { get; set; }
public Note Note { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
更改语句以使用新语句PersonNote.
var model = db.Notes
.Join(db.People, p => p.NotesListId, n => n.NotesListId,
((note, person) => new PersonNote { Note = note, Person = person }))
.ToList();
Run Code Online (Sandbox Code Playgroud)
改变模型.
@model IEnumerable<PersonNote>
Run Code Online (Sandbox Code Playgroud)