LINQ管理sql server数据库(增删改)

添加数据

         DataClasses1DataContext datacontent;
         string str = ConfigurationManager.AppSettings["SQLString"].ToString();

          datacontent = new DataClasses1DataContext(str); //实例化LINQ连接对象
          Message message = new Message();                        //实例化Message类对象
          message.Mess_Title = "new message";
          message.Mess_Content = "message content";
          datacontent.Message.InsertOnSubmit(message);  //将处于pending insert 状态的实体添加到sql数据表中,
          datacontent.SubmitChanges();                                  // 记录要插入,更新或删除的对象,并执行相应的命令以实现对数据库的更改

如果想实现使用数据库设置的默认值,那么就要修改LinqToSql文件相对应的列的属性  IsDbGenerated = true 

修改数据

DataClasses1DataContext datacontent;
string str = ConfigurationManager.AppSettings["SQLString"].ToString();

//查出要修改的实体
           datacontent = new DataClasses1DataContext(str);
           var data = from msg in datacontent.Message where msg.Mess_ID.ToString() == "7CE24F78-9B3C-44AD-B00B-908F3EA5C44D" select msg;

           //给实体赋予新的值
           foreach (Message item in data)
           {
               item.Mess_Title = "11";
               datacontent.SubmitChanges(); //提价修改,并修改数据库

           }

删除数据

DataClasses1DataContext datacontent;
string str = ConfigurationManager.AppSettings["SQLString"].ToString();

//查出要删除的实体

datacontent = new DataClasses1DataContext(str);
var data = from msg in datacontent.Message where msg.Mess_ID.ToString() == "7CE24F78-9B3C-44AD-B00B-908F3EA5C44D" select msg;
IEnumerable<Message> m = data;
datacontent.Message.DeleteAllOnSubmit(m);
datacontent.SubmitChanges();

你可能感兴趣的:(SQL Server)