参考 : http://msdn.microsoft.com/en-us/data/dn469464.aspx
EF 允许我们在发送SQL请求和返回数据时做一些拦截的动作
比如可以自定义写 log ,修改command , 修改result 等等
这里只是给一个简单的例子,以后有用到才研究吧.
public class EFInterceptorForSetTimeZone : IDbCommandInterceptor
{
public void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{ }
public void NonQueryExecuted( DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{ }
public void ReaderExecuting( DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
command.CommandText = "set time_zone = '-8:00';" + command.CommandText;
}
public void ReaderExecuted(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
//use table to load result then modify then convert back to reader
var dataTable = new DataTable();
dataTable.Load(interceptionContext.Result);
dataTable.Rows[]["id"] = ;
interceptionContext.Result = dataTable.CreateDataReader();
} public void ScalarExecuting( DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{ }
public void ScalarExecuted(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{ }
private void LogIfNonAsync<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{ }
private void LogIfError<TResult>(DbCommand command, DbCommandInterceptionContext<TResult> interceptionContext)
{ }
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
using (DB db = new DB())
{
DbInterception.Add(new EFInterceptorForSetTimeZone()); //添加一个拦截器 //拦截for写log, 放一个委托函数就可以了,
//msg 就是entity pass 进来的 string
//function (msg) { do something with no return.. };
db.Database.Log = msg =>
{
string y = msg;
};
var xyz = db.admins.ToList();
}
}
catch (Exception ex)
{
string x = ex.Message;
}
}