Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To set up Database First configuration in Entity Framework 7 for MVC 6, follow these steps:

  1. Create a new ASP.NET Core MVC 6 project in Visual Studio.
  2. Add a reference to the Microsoft.EntityFrameworkCore.Design package.
  3. Add a new folder to the root of your project and name it Models.
  4. In the Models folder, create a new class file and name it MyDbContext.cs.
  5. In MyDbContext.cs, add the following code:
using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

    public DbSet<MyEntity> MyEntities { get; set; }
}

Replace MyEntity with the name of your entity model.

  1. Use the Scaffold-DbContext command in the PMC (Package Manager Console) to generate the entity models from an existing database. For example:
Scaffold-DbContext "Server=localhost;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Replace the connection string and database name with your own.

  1. Build your project to ensure that the entity models have been generated.

  2. In Startup.cs, configure the DbContext with the connection string and add it to the dependency injection container:

using Microsoft.EntityFrameworkCore;

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<MyDbContext>(options =>
    {
        options.UseSqlServer(Configuration.GetConnectionString("MyDbConnection"));
    });
}

Replace MyDbContext and MyDbConnection with your own.

  1. You can now use the DbContext in your controllers to retrieve data from the database. For example:
public class HomeController : Controller
{
    private readonly MyDbContext _dbContext;

    public HomeController(MyDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IActionResult Index()
    {
        var myEntities = _dbContext.MyEntities.ToList();
        return View(myEntities);
    }
}