EF7: DBContext configuration on ASP.NET 5 Web-API

asp.net-core asp.net-web-api dbcontext entity-framework-core

Question

I'm currently developing an ASP.NET 5 Web-API application with VS2015 Ultimate Preview. Some things have changed about configuring EF7 on this new platform.

I've already checked the help in this page: https://github.com/aspnet/EntityFramework/wiki but it doesn't show all the step needed to successfully complete a connection with EF7 (it shows only a partial answer)

Can anyone bring a step-by-step tutorial on how would be the correct way to connect to a database (SQL Server) using EF7?. (not using old syntax like in MusicStore sample app but using more recent syntax)

Popular Answer

The code should be the same as you linked in the sample app. You register the context in Startup.cs, within ConfigureServices method using the following code:

public void ConfigureServices(IServiceCollection services)
{
    // Add EF services to the services container.
    services
        .AddEntityFramework(Configuration)
        .AddSqlServer()
        .AddDbContext<MyDbContext>(options =>
         {
             options.UseSqlServer(Configuration.Get("Data:DefaultConnection:ConnectionString"));
         });
}

Then your MyDbContext will be available for dependency injection, and in your controllers you can do

public MyController(MyDbContext context)
{
   ...
}

That's it




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why