简体   繁体   中英

How to Use Entity Framework 6.x in Asp.Net 5 (MVC 6)

I'm testing out the new Asp.Net 5, using VS 2015 CTP-6. Because of the lack of features in Entity Framework 7, I would prefer using EF6 for now.

I've tried removing EF7 and then applying EF6 in PM, like this:

Uninstall-Package EntityFramework
Install-Package EntityFramework -version 6.1.3

No errors returned, and the project.json file seems updated accordingly. Although, there are no DbContext available.

Is this at all possible? If yes, how should I proceed from here? Do I need web.config for EF6 compatibility?

Yes, this works fine.

You need to manually set the connection string when creating the context since it can't get it from the web.config

so you can do this

public class MyContext : DbContext {
    public MyContext(string connectionString) : base(connectionString) {
    }
}

var context = new MyContext("myConnectionString");

if you want to get the connection string from the config.json, then try this

IConfiguration configuration = new Configuration().AddJsonFile("config.json");
var connectionString = configuration["Data:DefaultConnection:ConnectionString"]);

and if you want to inject the context into the DI Container, then I added a factory like this

public static class MyContextFactory
{
    public static MyContext GetContext() {
        IConfiguration configuration = new Configuration().AddJsonFile("config.json");
        return new MyContext(configuration["Data:DefaultConnection:ConnectionString"]);
    }

}

and then added this in startup.cs

services.AddTransient<MyContext>((a) => MyContextFactory.GetContext());

Depending on database used it may not be as easy as answered. If you are using MsSql then no configuration is needed and the accepted answer is perfectly fine. But using LocalDB may need some configuration.

For example MySql needs to register provider

[DbConfigurationType(typeof(CodeConfig))] // point to the class that inherit from DbConfiguration
public class ApplicationDbContext : DbContext
{
    [...]
}

public class CodeConfig : DbConfiguration
{
    public CodeConfig()
    {
        SetDefaultConnectionFactory(new MySql.Data.Entity.MySqlConnectionFactory());
        SetProviderServices("MySql.Data.MySqlClient",
                    new MySql.Data.MySqlClient.MySqlProviderServices());
    }
}

PostgreSql needs to register provider into entityFramework AND system.data section. This may be done by using System.Data.Entity.DbConfiguration.Loaded event. Same goes with Oracle .

Check this blog post that explains it in details: http://bleedingnedge.com/2015/11/01/entity-framework-6-with-asp-net-5/

Can you not just do this in the startup.cs file? Save creating a factory

// new context on each request
services.AddScoped<IMyContext, MyContext>((s) =>
{
    return new MyContext(Configuration["Data:MyConnection:ConnectionString"]);
});

With the RC version, this becomes:

        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddEnvironmentVariables();
        var Configuration = builder.Build();
        var connectionString = Configuration["Data:DefaultConnection:ConnectionString"];

‌Before you start, make sure that you compile against full .NET Framework in your project.json as Entity Framework 6 does not support .NET Core. If you need cross platform features you will need to upgrade to Entity Framework Core.

In your project.json file specify a single target for the full .NET Framework:

"frameworks": {
    "net46": {}
}

and then Setup connection strings and dependency injection

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
    {
    }
}

In the Startup class within ConfigureServices add factory method of your context with it's connection string. Context should be resolved once per scope to ensure performance and ensure reliable operation of Entity Framework.

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped((_) => new ApplicationDbContext(Configuration["Data:DefaultConnection:ConnectionString"]));

    // Configure remaining services
}

ntity Framework 6 allows configuration to be specified in xml (in web.config or app.config) or through code. As of ASP.NET Core, all configuration is code-based.

Code-based configuration is achieved by creating a subclass of System.Data.Entity.Config.DbConfiguration and applying System.Data.Entity.DbConfigurationTypeAttribute to your DbContext subclass.

Our config file typically looked like this:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="mssqllocaldb" />
        </parameters>
    </defaultConnectionFactory>
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
</entityFramework>

The defaultConnectionFactory element sets the factory for connections. If this attribute is not set then the default value is SqlConnectionProvider . If, on the other hand, value is provided, the given class will be used to create DbConnection with its CreateConnection method. If the given factory has no default constructor then you must add parameters that are used to construct the object

[DbConfigurationType(typeof(CodeConfig))] // point to the class that inherit from DbConfiguration
public class ApplicationDbContext : DbContext
{
    [...]
}

public class CodeConfig : DbConfiguration
{
    public CodeConfig()
    {
        SetProviderServices("System.Data.SqlClient",
            System.Data.Entity.SqlServer.SqlProviderServices.Instance);
    }
}

This article will show you how to use Entity Framework 6 inside an ASP.NET Core application. https://docs.asp.net/en/latest/data/entity-framework-6.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM