LINQ的最簡單的增刪改查寫法
阿新 • • 發佈:2017-12-14
sin 提交 pos 精確 lis show text name 直接
.ToList();//返回一個集合,包含查到的所有值;
.First();//返回查到的第一條數據,如果查不到會報錯;
.FirstOrDefault();返回查到的第一條數據,差不到返回一個null;
db.Users.InsertOnSubmit();//添加
db.DeleteOrSubmit();//刪除
db.SubmitChanges();//提交修改,增刪改都需要提交;
//修改取到對象之後直接賦值,提交;
//基礎查,把內容放到泛型集合 using(DBDataContext db = new DBDataContext()) { List<Users> ulist = db.Users.ToList(); }//模糊差,contains包含 string a = "123"; using(DBDataContext db = new DBDataContext()) { List<Users> ulist = db.Users.where(r => r.Ids.Contains(a))ToList(); } //精確查, string a = "123"; using(DBDataContext db = new DBDataContext()) { List<Users> ulist = db.Users.where(r => r.Ids==a)ToList(); }//添加 Users u = new Users(); u.ids = "1"; u.UserName = "2"; u.password = "3"; using(DBdataContext db = new DBDataTaxt()) { try { db.Users.InsertOnSubmit(u); db.SubmitChanges(); MessageBox.Show("成功"); } catch { MessageBox.Show("失敗"); } } //修改 string a = "1"; using(DBdataContext db = new DBDataTaxt()) {try { Users u = db.Usres.where(r => r.ids == a).FirstOrDefault(); u.ids = "3"; u.UserName = "2"; u.password = "1"; db.SubmitChanges(); MessageBox.Show("成功"); } catch { MessageBox.Show("失敗"); } } //刪除 string a = "1"; using(DBdataContext db = new DBDataTaxt()) { List<Users> ulist = db.Users.where(r => r.Ids == a).ToList(); if(ulist.Count > 0) { db.DeleteOnSubmit(ulist[0]); db.SubmitChanges(); } }
LINQ的最簡單的增刪改查寫法