从上到下列出的是SQL的编写顺序;
然后编号代表的是Linq的编写顺序
具体的查询操作
小工具 Linq Pad的学习使用,可以将linq SQL代码互相转换
使用数据库:NorthWind示例数据库 (链接:https://www.cnblogs.com/liverpool/p/4718042.html)
1.Linq写法
后台代码:
注意:查询单列和多列的时候需要修改强类型视图,我这里是新建了ViewModels文件夹,然后自定义了专门用于视图显示的CustomerModel;
分页中的OrderBy和Skip以及Take都是属于方法特有的,不是Linq中的(可以混写);
namespace T1_EF.Controllers { public class CustomersController : Controller { // GET: Customers public ActionResult Index() { //NorthwindEntities northwind = new NorthwindEntities(); //var list = northwind.Customers.Select(c =>c); //建议使用下面这种写法,面向抽象编程,使用多态,并且更灵活 //DbContext dbContext = new NorthwindEntities(); //var list = dbContext.Set().Select(c => c); //使用Linq练习操作 dynamic list; DbContext db = new NorthwindEntities(); //基本查询 //list = from customer in db.Set() select customer; //单条件查询 //list = from customer in db.Set() where customer.Country == "USA" select customer; //多条件查询 //list = from customer in db.Set() // where customer.Country == "USA" || customer.Country == "Canada" // select customer; //查询单列(这样就不能使用强类型视图了) //list = from customer in db.Set() select customer.Country; //查询多列(将select后换为匿名对象或者要展示的对象)(建议新增viewModel作为视图对象,否则在前台数据必须进行反序列化操作) //list = from customer in db.Set() select new CustomerModel{ ContactName= customer.ContactName,CompanyName= customer.CompanyName }; //分页,Skip就是跳过元素,Take就是要返回排在前面的几个元素,一般与OrderBy排序使用(注意:是方法特有的,不是Linq写法) list = (from customer in db.Set() select customer).OrderBy(c=>c.CompanyName).Skip(5).Take(15); ViewData.Model = list; return View(); } } }
前台代码:
@*@model IQueryable<T1_EF.ViewModels.CustomerModel>*@ @model IQueryable<T1_EF.Models.Customers> @{ Layout = null; } DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Indextitle> head> <body> <div> <table border="1"> <tr> <td>客户公司td> <td>联系人姓名td> <td>地址td> <td>国家td> tr> @foreach (var item in Model) { <tr> <td>@item.CompanyNametd> <td>@item.ContactNametd> <td>@item.Addresstd> <td>@item.Countrytd> tr> } table> div> body> html>
End