1. 程式人生 > >asp.net MVC + EF , Linq的基本用法

asp.net MVC + EF , Linq的基本用法

top code sum 裏的 頁碼 reac style from sta

 public ActionResult Index()
        {
            NewsEntities news = new NewsEntities();

            //select * from NewsInfo

            #region 排序
            var query = from s in news.NewsInfo
                        orderby s.ID descending   //ascending
                        select new { id = s.ID, name = s.Name, auter = s.Auter };   //
構造屬性 foreach (var item in query) { int id = item.id; string name = item.name; } #endregion #region where條件 + top //var query1 = from s in news.NewsInfo // where s.ID >= 1 && s.ID <= 6
// select s; var query1 = (from s in news.NewsInfo where s.Name.StartsWith("") //EndsWith : name like ‘%啊‘ ,Contains : name like ‘%啊%‘ , StartsWith : name like ‘啊%‘ select s).Take(3); //take() 類似top foreach (var item in
query1) { int id = item.ID; string name = item.Name; } #endregion #region 函數 var query2 = from s in news.NewsInfo group s by new { s.ID, s.Time } into tab select tab; //int? sum = query3.Sum(f => f.Key.ID); //System.DateTime? maxid = query3.Max(f => f.Key.Time); foreach (var item in query2) { var id = item.Key.ID; var time = item.Key.Time; //統計一組數據記錄數 int count = item.Count(); //計算一組的平均ID double? avg = item.Average(f => f.ID); //計算ID之和 int? sum = item.Sum(f => f.ID); //統計當前最大 最小的ID數 int? maxid = item.Max(f => f.ID); int? minid = item.Min(f => f.ID); } #endregion #region skip(跳過指定前幾行) + take(再獲取前幾行) var query3 = (from s in news.NewsInfo orderby s.ID ascending select s).Skip(2).Take(3); //take() 類似top foreach (var item in query3) { int id = item.ID; string name = item.Name; } #endregion #region linq 分頁操作 //當前頁碼 int pageindex = 1; //每頁數量 int pagesize = 2; var list = (from s in news.NewsInfo orderby s.ID ascending select s).Skip((pageindex - 1) * pagesize).Take(pagesize); #endregion #region 鏈表查詢(查詢數據裏的所有男女性別 並輸出男女性別數量) var list1 = from ss in ( from s in news.NewsInfo join g in news.GTable on s.ID equals g.ID select new { id = s.ID, name = s.Name, gsex = g.Sex } ) group ss by ss.gsex into tab select tab; foreach (var item in list1) { var Class = item.Key; var count = item.Count(); } #endregion #region 子表查詢(用b表的ID查詢a表的name列) var zi = from b in news.GTable select new { id = b.ID, name = ( from a in news.NewsInfo where b.ID == a.ID select a.Name ).FirstOrDefault() }; foreach (var item in zi) { var name = item.id; var gname = item.name; } #endregion return View(); }

asp.net MVC + EF , Linq的基本用法