How to configure ProviderManifestToken for EF Code First

后端 未结 10 1155
-上瘾入骨i
-上瘾入骨i 2020-11-27 05:49

I have a asp.net MVC3 project using EF code-first. For my unit testing I have been using SQL Server CE 4.0 and SQL Server 2008 Express. Both have worked perfectly with EF ge

10条回答
  •  日久生厌
    2020-11-27 06:36

    After hours of searching & fiddling, I found a way to do it. Turns out the DbModelBuilder class takes a DbProviderInfo in its Build method, so I use that instead of relying on EF to call OnModelCreated:

    // 'Entities' is my DbContext subclass, the "container" in EF terms.
    public static Entities GetNewContext()
    {
        // Get a connection, for example:
        var connection = new SqlConnection(GetConnectionString());
    
        // Create a DbModelBuilder
        var modelBuilder = new DbModelBuilder();
        // Configure the model builder.
        // I changed my DbContext subclass - added a public version of OnModelCreated and called it ConfigureModelBuilder
        Entities.ConfigureModelBuilder(modelBuilder);
    
        // Here's where the magic happens.
        // Build the model and pass the ProviderManifestToken (I use 2005 to avoid a bug in precision of sql datetime columns when using concurrency control)
        var model = modelBuilder.Build(new System.Data.Entity.Infrastructure.DbProviderInfo("System.Data.SqlClient", "2005"));
        // Compile the model
        var compiledModel = model.Compile();
    
        // Create the container (DbContext subclass). Ideally all the previous stuff should be cached.
        return new Entities(connection, compiledModel, true);
    }
    

    Obviously this needs some reorganization (e.g. cache the compiled model so you don't need to re-build it every time a context is created).

    For me this completely solved the problem. Enjoy!

提交回复
热议问题