MiniProfiler网站提供了以下用于生成实体框架ObjectContext的代码:
The MiniProfiler site gives the following code for generating an Entity Framework ObjectContext:
public static MyModel Get() { var conn = new StackExchange.Profiling.Data.EFProfiledDbConnection(GetConnection(), MiniProfiler.Current); return ObjectContextUtils.CreateObjectContext<MyModel>(conn); // resides in the MiniProfiler.EF nuget pack }但是,使用Entity Framework 5,我没有使用ObjectContext-而是使用了DbContext.我不能在此处插入型号名称,因为CreateObjectContext<T>()方法期望T的类型为ObjectContext. (出于同样的原因,此答案中给出的代码也不起作用).
However, using Entity Framework 5, I am not using an ObjectContext - rather I am using a DbContext. I cannot plug the model name in here, since the CreateObjectContext<T>() method expects T to be of type ObjectContext. (For the same reason, the code given in this answer also doesn't work).
此外,我正在使用autofac初始化我的Db连接.正在使用以下内容(MyData =我的EF DataContext的名称)进行注册:
Additionally, I am using autofac to initialize my Db connections. This is being registered with the following (MyData = the name of my EF DataContext):
Builder.RegisterType<MyData>().As<DbContext>().InstancePerHttpRequest();因此结合了两个部分:如何使用autofac初始化绑定到MiniProfiler.EF的DbContext?如果不可能,那么至少我该如何做第一部分(为MiniProfiler.EF创建工厂方法以返回DbContext)?
So combining two parts: how can I use autofac to initialize my DbContext tied into MiniProfiler.EF? And if that is not possible, at least how can I do the first part (create a factory method for MiniProfiler.EF to return a DbContext)?
推荐答案有一个DbContext类的.aspx"rel =" noreferrer>构造函数,它采用现有的DbConnection
There is a constructor of the DbContext class which takes an existing DbConnection
因此,您在MyData上需要一个新的构造器,该构造器仅调用基础
So you need a new contructor on your MyData which just calls the base
public class MyData : DbContext { public MyData(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } //.. }然后您将MyData注册到Register:
builder.Register(c => { var conn = new EFProfiledDbConnection(GetConnection(), MiniProfiler.Current); return new MyData(conn, true); }).As<DbContext>().InstancePerHttpRequest();更多推荐
使用MiniProfiler和EF 5和Autofac剖析DbContext的正确方法
发布评论