1 | initial version |
To set up Database First configuration in Entity Framework 7 for MVC 6, follow these steps:
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.
Scaffold-DbContext "Server=localhost;Database=mydb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
Replace the connection string and database name with your own.
Build your project to ensure that the entity models have been generated.
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.
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);
}
}