@model IQueryable<EFExam.Models.ProductViewModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table border="1">
<tr>
<th>ModelNumber</th>
<th>ModelName</th>
</tr>
@* @foreach (EFExam.Models.Product p in Model)
{
<tr><td>@p.ModelNumber</td><td>@p.ModelName</td></tr>
}*@
@foreach(EFExam.Models.ProductViewModel p in Model)
{
<tr><td>@p.Number</td><td>@p.Name</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 ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
DbContext context = new StoreContext();
//StoreContext context = new StoreContext();
//linq
IQueryable<Product> list;
//list = from p in context.Products select p;
//基本查询
//list = from p in context.Set<Product>() select p;
list = context.Set<Product>().Select(p => p);
//单条件查询
//list = from p in context.Set<Product>() where p.ProductID < 3 select p;
list = context.Set<Product>().Where(p => p.ProductID < 3);
//多条件查询
//list = from p in context.Set<Product>() where p.ProductID < 3 && p.ProductID>2 select p;
list = context.Set<Product>().Where(p => p.ProductID < 3 && p.ProductID > 2);
//单列查询
//var list1 = from p in context.Set<Product>() select p.ModelName;
var list1 = context.Set<Product>().Select(p => p.ProductID);
//查询多列 定义ViewMode
//var list2 = from p in context.Set<Product>() select new ProductViewModel{Number = p.ModelNumber,Name=p.ModelName};
var list2 = context.Set<Product>().Select(p => new ProductViewModel(){ Number = p.ModelNumber, Name = p.ModelName });
//分页查询 //必须排序后
list = context.Set<Product>().OrderBy(p=>p.ModelName).Skip(1).Take(1);
//方法
//var list = context.Products.Select(p => p);
return View(list2);
}
}
}