public ViewResult Index(...)
{
var newlist = from n in db.students
join o in db.info on n.id equals o.id
select n;
// ^ This only select collection from "students" as "n".
return View(newlist.ToPagedList(..., ...));
// ^ using PagedList Extenstion
}
I want to join to some others tables and get some additional columns.
Any chance to use it in cshtml file (View) like this?:@foreach (var item in Model) {
<td>@item.column_from_students_table_1</td>
<td>@item.column_from_students_table_2</td>
<td>@item.column_from_info_table_1</td>
<td>...</td>
}
You could create your own custom view type and select to that:
ViewModel:
public class StudenInfoView
{
//From Students
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
//From info
public int Age { get; set; }
}
Linq Query:
var newlist = (from n in db.students
join o in db.info on n.id equals o.id
select new StudenInfoView {
Id = n.Id,
FirstName = n.FirstName,
LastName = n.LastName,
Age = o.Age
});
Since you are passing your Entity directly to your view that comes from some ORM provider (probably L2S or entity framework) so you can use properties both from student and info tables. You can perfectly fetch columns from student's table using
<td>@item.column_from_students_table_1</td>
<td>@item.column_from_students_table_2</td>
when it comes to fetching columns from info table, it depends upon relationship between two tables (if it is created in db). if student class (created by your mapper) has property of type EntitySet you can access columns from info table like
<td>@item.Infos.FirstOrDefault().Column_from_info_table</td>
Word of Caution: It is not recommended to pass your model directly to your view. you can rather make a view model that is tailored to the needs of that particular view and you can populate and pass this view model to the view.
精彩评论