首先新建一个Console Application项目:ISPLinqDemo
在数据库中新建一个表:tb_Test
---------------------------------------
UserID | int | primary key
---------------------------------------
UserName | nvarchar(50) |
---------------------------------------
然后在资源解决方案中右击添加项"LINQ to SQL Classes",命名为:TestData
然后从Server Explorer中将表tb_Test拖到新建的"LINQ to SQL Classes"。
此时,会自动生成一些相关的变量与操作。比如TestDataDataContext等。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ISPLinqDemo
{
class Program
{
static void Main(string[] args)
{
/*
// SelectData
int id = 1;
IEnumerable tests = LinqOperations.SelectData(id);
foreach (var test in tests)
{
Console.WriteLine("ID: " + test.UserID + "\tName: " + test.UserName);
}
*/
/*
//InsertData
tb_Test testmp = new tb_Test();
testmp.UserID = 403;
testmp.UserName = "403";
if (LinqOperations.InsertData(testmp) == true)
Console.WriteLine("数据插入成功!");
*/
/*
// UpdateData
int updateID = 403;
tb_Test newTest = new tb_Test();
newTest.UserName = "ISP";
if (LinqOperations.UpdateData(newTest, updateID) == true)
Console.WriteLine("数据更新成功!");
*/
/*
// DeleteData
int deleteID = 1;
if (LinqOperations.DeleteData(deleteID) == true)
Console.WriteLine("数据删除成功!");
*/
Console.ReadKey();
}
}
class LinqOperations
{
private static TestDataDataContext db;
///
/// 初始化DataContext
///
///
private static void LinqOperationInit()
{
if (db == null)
db = new TestDataDataContext();
}
///
/// 插入数据
/// ///
///
插入是否成功 public static bool InsertData(tb_Test test)
{
LinqOperationInit();
try
{
db.tb_Tests.InsertOnSubmit(test);
db.SubmitChanges();
return true;
}
catch (Exception err)
{
Console.WriteLine("数据插入失败:" + err);
return false;
}
}
///
/// 筛选数据
/// ///
///
筛选指定ID的结果集 public static IEnumerable
SelectData(int ID)
{
LinqOperationInit();
try
{
var data = from test in db.tb_Tests
where test.UserID == ID
select test;
return data;
}
catch (Exception err)
{
Console.WriteLine("数据查询失败:" + err);
return null;
}
}
///
/// 更新数据
/// ///
///
///
更新是否成功 public static bool UpdateData(tb_Test test, int ID)
{
LinqOperationInit();
try
{
var data = from testmp in db.tb_Tests
where testmp.UserID == ID
select testmp;
foreach (tb_Test newTest in data)
{
newTest.UserName = test.UserName;
}
db.SubmitChanges();
return true;
}
catch (Exception err)
{
Console.WriteLine("数据更新失败:" + err);
return false;
}
}
///
/// 删除数据
/// ///
///
删除是否成功 public static bool DeleteData(int ID)
{
LinqOperationInit();
try
{
var data = from test in db.tb_Tests
where test.UserID == ID
select test;
if (data.Count
() > 0)
{
db.tb_Tests.DeleteOnSubmit(data.First());
db.SubmitChanges();
return true;
}
else
{
Console.WriteLine("数据删除失败!");
return false;
}
}
catch (Exception err)
{
Console.WriteLine("数据删除失败:" + err);
return false;
}
}
}
}
阅读(2120) | 评论(0) | 转发(0) |