LinQ中增删改语句如何写

如题,有代码更佳
2024-12-18 14:53:33
推荐回答(2个)
回答1:

我们知道LINQ中的增删改都要调用SubmitChanges方法,我们记录所有SQL的方式就是重写(override)DataContext中的SubmitChanges方法,为了避免每次修改dbml文件时影响我们自己写的内容,我们要先写一个DataContext的分布类,在这个类中重写SubmitChanges方法。
代码如下
Code
public partial class DataClasses1DataContext
{
public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{
//记录日志(每天一个文件,记录所有更改sql,日志会存在第一个盘的log文件夹下)
string directory = Path.Combine(Directory.GetLogicalDrives().First(), "log");
Directory.CreateDirectory(directory);
string logFile = Path.Combine(directory,
"log" + DateTime.Now.ToLongDateString() + ".txt");
using (StreamWriter w = File.AppendText(logFile))
{

w.WriteLine("发生时间:{0}", DateTime.Now.ToString());
w.WriteLine("日志内容为:");
this.Log = w;
try
{
base.SubmitChanges(failureMode);
}
catch (Exception e)
{
w.WriteLine("异常:" + e.Message + e.StackTrace);
w.WriteLine("--------------------------------------------------------------");

throw;
}
finally
{
this.Log = null;
}
w.WriteLine("--------------------------------------------------------------");

}

}
}

回答2:

我还是贴代码吧,说是说不明白的。。。
以下是我的一个项目里面的节选,分别实现了增删查改功能,你可以看看LINQ对数据的操作。
///


/// Select
///

///
public IQueryable Linqmy()
{
var my = from s in db.account select s;
return my;
}

///
/// Insert
///

///
///
///
public bool LinqInsertmy(string name,string pwd)
{
account account = new account();
account.name = name;
account.pwd = pwd;
db.account.InsertOnSubmit(account);
db.SubmitChanges();
return true;
}

///
/// Delete
///

///
///
public bool LinqDelete(int id)
{
account account = db.account.Single(a => a.id == id);
db.account.DeleteOnSubmit(account);
db.SubmitChanges();
return true;
}

///
/// Update
///

///
///
///
///
public bool LinqUpdate(int id, string name, string pwd)
{
account account = db.account.Single(a => a.id == id);
account.name = name;
account.pwd = pwd;
db.SubmitChanges();
return true;
}