当前位置:Gxlcms > 数据库问题 > 利用LINQ to SQL 增删改查本地数据库

利用LINQ to SQL 增删改查本地数据库

时间:2021-07-01 10:21:17 帮助过:2人阅读

  1. LINQ to SQL查询数据库
    //查询数据库
    using (DbAppDataContext context = new DbAppDataContext())
    {
           context.Log = Console.Out;
           var query = from p in context.PeopleInfoTables
                       let length = p.Names.Length
                       orderby length
                       select new { Name = p.Names, Length = length };
           foreach (var entry in query)
           {
                 Console.WriteLine("{0}:{1}", entry.Name, entry.Length);
           }
    }

    输出结果
    技术分享
     
  2. LINQ to SQL增加数据库信息
    //往数据库增加信息
    using (DbAppDataContext context = new DbAppDataContext())
    {
         context.Log = Console.Out;
         context.PeopleInfoTables.InsertOnSubmit(new PeopleInfoTable
         {
             Names = "Qinan",
             Addresses = "Shaoxing",
             Ages = 24,
             ID = "1231231",
             Nations = "China",
             Phones = "18868875132"
          });
          context.SubmitChanges();
          var query = from p in context.PeopleInfoTables
              select new { Name = p.Names, Address = p.Addresses };
          foreach (var entry in query)
          {
              Console.WriteLine("{0}:{1}", entry.Name, entry.Address);
          }
    }

    输出结果
    技术分享
     
  3. LINQ to SQL删除数据库信息
    //删除数据库某条信息
    using (DbAppDataContext context = new DbAppDataContext())
    {
          context.Log = Console.Out;
          var people = context.PeopleInfoTables.SingleOrDefault(p => p.Names == "Qinan");
          if (people != null)
          {
              context.PeopleInfoTables.DeleteOnSubmit(people);
              context.SubmitChanges();
          }
          var query = from p in context.PeopleInfoTables
               select new { Name = p.Names, Address = p.Addresses };
          foreach (var entry in query)
          {
               Console.WriteLine("{0}:{1}", entry.Name, entry.Address);
          }
    }

    输出结果
    技术分享
  4. LINQ to SQL编辑数据库
    //编辑数据库中的信息
    using (DbAppDataContext context = new DbAppDataContext())
    {
        context.Log = Console.Out;
        var people = context.PeopleInfoTables.SingleOrDefault(p => p.Names == "Yuan");
        if (people != null)
        {
            people.Ages = 50;
            people.Addresses = "tanggu";
            context.SubmitChanges();
        }
        var query = from p in context.PeopleInfoTables
             select new {Name = p.Names, Age = p.Ages, Address = p.Addresses};
        foreach (var entry in query)
        {
             Console.WriteLine("{0}:{1},{2}", entry.Name, entry.Age, entry.Address);
        }
    }

    输出结果
    技术分享

     

利用LINQ to SQL 增删改查本地数据库

标签:

人气教程排行