1

我觉得我在这里遗漏了一些非常简单的东西,我正在将 MVC Miniprofiler 集成到我的项目中,但是我找不到用正确的连接实例化我的上下文的方法,因为它不是 EF Code First 并且我的模型继承自 ObjectContext,在这里是我的代码

public static MyModel GetDataBaseModel()
{       
    DbConnection conn = new MySqlConnection(Utils.GetConnectionString());

    // this returns a DBConnection
    DbConnection profiledConnection = MvcMiniProfiler.Data.ProfiledDbConnection.Get(conn);  

    //my model needs an EntityConnection, so this is not possible
    return new MyModel(profiledConnection); 
}

如何解决这个问题?

4

1 回答 1

1

我假设这MyModel是实体框架设计器创建的上下文,对吧?EntityConnection 可以从 DbConnection 与MetadataWorkspace. 我还假设 EF 设计器已向您的 app/web.config 添加了一个连接字符串属性,其中包含如下内容:

metadata=res://*/Content.MyModel.csdl|res://*/Content.MyModel.ssdl|res://*/Content.MyModel.msl;

这些是构成 MetadataWorkspace 的 3 个组件。要根据这些信息创建 EntityConnection,您必须在数组中提供每个文件:

string[] paths =
{
    // "res://" refers to a embedded resource within your DLL, this is automatically done if
    // you've used the EF designer.
    "res://*/Content.MyModel.csdl",
    "res://*/Content.MyModel.ssdl",
    "res://*/Content.MyModel.msl"
};

Assembly[] assembliesToConsider = new Assembly[]
{
    typeof(MyModel).Assembly
};

System.Data.Metadata.Edm.MetadataWorkspace workspace = new System.Data.Metadata.Edm.MetadataWorkspace(paths, assembliesToConsider);
EntityConnection connection = new EntityConnection(workspace, profiledConnection);

我没有用 MvcMiniProfiler 测试过(现在第一次安装它),但可能存在一些问题,如果配置文件的连接与原始 MySqlConnection 的行为不完全一样,请尝试一下,否则将尝试创建您的设置.

于 2011-08-11T21:43:46.673 回答