Linq学习比较第2篇
参考程序:
//增
t_User user = new t_User();
user.UserName = "大气象";
user.Pwd = "123456";
ctx.t_User.InsertOnSubmit(user);//以前的方法是Add();
ctx.SubmitChanges();
//改
//参考这样的语法string s = (from a in ctx.Customers select a).Single(a => a.ID == 2);
t_User userUpdate = ctx.t_User.SingleOrDefault(t_User => t_User.ID == 2);//Single与SingleOrDefault没区别
userUpdate.UserName = "大气象1";
ctx.SubmitChanges();
//删
t_User userDelete = (from userinfo in ctx.t_User where userinfo.ID == 1 select userinfo).FirstOrDefault();
if (userDelete != null)
{
ctx.t_User.DeleteOnSubmit(userDelete);
ctx.SubmitChanges();
}
自己的程序:
NorthwindDataContext dc = new NorthwindDataContext(@"Data Source=.\SQLEXPRESS;AttachDbFilename='c:\documents and settings\administrator\my documents\visual studio 2010\Projects\test\test\test.mdf';Integrated Security=True;User Instance=True");
studentInfo stuInfo = new studentInfo();
stuInfo.StudentName = "陈小春";
stuInfo.studentAge = 35;
dc.studentInfo.InsertOnSubmit(stuInfo);
dc.SubmitChanges();
//修改
studentInfo updateInfo = dc.studentInfo.SingleOrDefault(studentInfo => studentInfo.studentid == 2);
updateInfo.StudentName = "刘德华";
dc.SubmitChanges();
//删除
studentInfo deleteInfo = (from userinfo in dc.studentInfo where userinfo.studentid == 1 select userinfo).SingleOrDefault();
if(deleteInfo!=null)
{
dc.studentInfo.DeleteOnSubmit(deleteInfo);
dc.SubmitChanges();
}