Linq to sql 操作

1.往数据库添加数据

 1             NorthwindDataContext abc = new NorthwindDataContext();
 2             abc.Log = Console.Out;
 3             User a = new User();
 4             {
 5                 a.id = 11;
 6                 a.password = "11";
 7                 a.username = "11";
 8                 
 9             }
10             abc.User.InsertOnSubmit(a);
11             abc.SubmitChanges();
12             Console.Write(a.id+a.password+a.username);

2.查询数据库中的数据

1  //查询
2             NorthwindDataContext abc = new NorthwindDataContext();
3             abc.Log = Console.Out;
4             User a = abc.User.Where(o => o.id.Equals("2")).Single();
5             Console.Write(a.id+a.password);

3.修改数据库中的数据

            //修改
            NorthwindDataContext abc = new NorthwindDataContext();
            abc.Log = Console.Out;
            User a = abc.User.Where(o => o.id.Equals("2")).Single();
            a.password = "12";
            abc.SubmitChanges();
            Console.Write(a.id + a.password);

4.删除数据

            //删除
            NorthwindDataContext abc = new NorthwindDataContext();
            abc.Log = Console.Out;
            IQueryable<User> a = abc.User.Where(o => o.id.Equals("2"));
            abc.User.DeleteAllOnSubmit(a);
            abc.SubmitChanges();

 注意:在删除操作中 DeleteAllOnSubmit 方法的参数是可枚举类型的,如果换成下面的代码则不能执行删除操作

            //删除
            NorthwindDataContext abc = new NorthwindDataContext();
            abc.Log = Console.Out;
            User a = abc.User.Where(o => o.id.Equals("2")).Single();
            abc.User.DeleteAllOnSubmit(a);
            abc.SubmitChanges();

 这里的第三行代码和上面的代码的是不同的,上面的变量a是集合(可枚举),下面的a则是单一的数

 

 

posted @ 2013-12-01 10:47  naraku666  阅读(147)  评论(0编辑  收藏  举报