@model IQueryable<EFExam.Models.CategoryProductViewModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
<tr>
<th>CategoryName</th>
<th>ProductName</th>
</tr>
@foreach (EFExam.Models.CategoryProductViewModel cp in Model)
{
<tr>
<td>@cp.NCategoryName</td><td>@cp.NProductName</td>
</tr>
}
</table>
</div>
</body>
</html>
using EFExam.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EFExam.Controllers
{
public class CategoryController : Controller
{
//
// GET: /Category/
public ActionResult Index()
{
DbContext context = new StoreContext();
//var list = from category in context.Set<Category>()
// join product in context.Set<Product>()
// on category.CategoryID equals product.CategoryID
// select category;
//导航属性 第一种方法1对多 多from语句
//var list = from category in context.Set<Category>()
// from product in category.Products
// select new CategoryProductViewModel
// {
// NCategoryName = category.CategoryName,
// NProductName = product.ModelName
// };
//导航属性 第二种方法多对1
var list = from product in context.Set<Product>()
select new CategoryProductViewModel()
{
NCategoryName = product.Category.CategoryName,
NProductName = product.ModelName
};
return View(list);
}
}
}