漫话Linq——Linq To SQL
Linq 是 .Net 框架里面一项强大、实用的技术!根据操作对象不同可分为四类:Linq To Object、Linq To SQL、Linq To DataSet、Linq To XML
如下所示演示的是Linq To SQL基本的 增、删、改、查用法,供大家互相学习之用。
#region 全局变量
/// <summary>
/// Linq to Sql 类
/// </summary>
DataClassesDataContext dc = new DataClassesDataContext();
#endregion
#region 查询
/// <summary>
/// 查询信息
/// </summary>
/// <param name="where"></param>
/// <returns></returns>
public IList<EA_Script> getWhere(String whereInfo)
{
/*
* 还可以使用 Where + Contains() 实现模糊查询
* 例:var query = from es in dc.EA_Script
where es.Title.Contains(keyWorld)
orderby es.Id descending
select es;
*/
String strSQL = "SELECT * FROM EA_Script es WHERE " + whereInfo + " ORDER BY es.Id DESC";
var query = dc.ExecuteQuery<EA_Script>(strSQL);
return query.ToList();
}
#endregion
#region 删除
/// <summary>
/// 删除
/// </summary>
/// <param name="Id"></param>
/// <returns></returns>
public bool Delete(int Id)
{
/*
* 删除信息:
* 方法一,使用 DeleteOnSubmit(实体类) 方法;
* 例:见下文
* 方法二,使用 ExecuteCommand(T-SQL 语句) 方法;
* 例:dc.ExecuteCommand(" DELETE FROM EA_Script WHERE Id = " + Id);
*/
EA_Script entity = new EA_Script();
var query = (EA_Script)dc.EA_Script.FirstOrDefault(item => item.Id == Id);
if (query != null)
{
try
{
entity = (EA_Script)query;
/*
* 写法二:
* dc.GetTable<EA_Script>().DeleteOnSubmit(entity);
*/
dc.EA_Script.DeleteOnSubmit(entity);
dc.SubmitChanges(); //保存修改,一定不要忘记
return true;
}
catch
{
return false;
}
}
else
return false;
}
#endregion
#region 修改
/// <summary>
/// 修改
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Update(EA_Script entity)
{
try
{
EA_Script es = dc.EA_Script.FirstOrDefault<EA_Script>(item => item.Id == entity.Id);
if (es != null)
{
es.Title = entity.Title;
es.Detail = entity.Detail;
es.DateTime = entity.DateTime;
es.Downloads = entity.Downloads;
es.FName = entity.FName;
dc.SubmitChanges();
return true;
}
else
return false;
}
catch
{
return false;
}
}
#endregion
#region 添加
/// <summary>
/// 添加
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Insert(EA_Script entity)
{
/*
* 写法二:
* dc.GetTable<EA_Script>().InsertOnSubmit(entity);
*/
try
{
dc.EA_Script.InsertOnSubmit(entity);
dc.SubmitChanges();
return true;
}
catch
{
return false;
}
}
#endregion