Ask Your Question
2

How to set up Database First configuration in Entity Framework 7 for MVC 6?

asked 2023-03-12 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-03-30 17:00:00 +0000

woof gravatar image

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);
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-12 11:00:00 +0000

Seen: 17 times

Last updated: Mar 30 '23