Entity Framework 6 set connection string runtime

后端 未结 3 727
日久生厌
日久生厌 2020-12-08 07:50

We are in a mixed environment where our application is using both ADO.NET and Entity Framework.
Since both are pointing to the same physical SQL server, we would like to

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 08:17

    You are getting the Code First mode exception because you are passing a DbConnection built with the ADO.NET connection string. This connection string does not include references to metadata files, so EntityFramework does not know where to find them.

    To create a DbContext with an appropriate programmatically set connection string, use the EntityConnectionStringBuilder class.

    var entityBuilder = new EntityConnectionStringBuilder();
    
    // use your ADO.NET connection string
    entityBuilder.ProviderConnectionString = conString;
    
    // Set the Metadata location.
    entityBuilder.Metadata = @"res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl";
    var dbContext = new DbContext(entityBuilder.ConnectionString);
    

提交回复
热议问题