Home > Enterprise >  EntityFramework dependency injection of DatabaseContext on Asp.Net
EntityFramework dependency injection of DatabaseContext on Asp.Net

Time:01-27

i have not much knowledge about Asp and Entity Framework so i really cant figure out what i have to do. My problem is accessing database context out of main asp method - There is how db context created and used in Program.cs (Main)

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<DatabaseContext>(
    options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultDataSource"))
);

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var context = services.GetRequiredService<DatabaseContext>();
    context.Database.EnsureCreated();
}

so my problem is kinda that i making "options" for DatabaseContext constructor out of "builder.Configuration"

But what do i do when i need to acces db from other script? DatabaseContext requires config but i just dont know how to get it outside of that builder. one guy suggested me to use Dependency Injection, i have looked but i just cant get how to do it properly, like i make a class where i initialize db context, but i still need to somehow make a config here and i really have no clue how. It could be really stupid question but i really cant figure it out for a couple of days :D

I`ve tried to make DbContext without a config but it gives error

CodePudding user response:

I don't know what you tried, but I think this might be what you want.

Assuming your DatabaseContext class is the most basic, and defines a table Users in it:

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

    public DbSet<Models.User> Users { get; set; }
}

Then you register it in Program.cs:

builder.Services.AddDbContext<DatabaseContext>(
    options => options.UseSqlite(builder.Configuration.GetConnectionString("DefaultDataSource"))
);

You can generate your database by migrating and updating the database(Of course you can also manually create):

Add-Migration InitialCreate
Update-Database

Then you can access your database in other classes through dependency injection, such as in the controller:

public class HomeController : Controller
{
    private readonly DatabaseContext _databaseContext;
    public HomeController(DatabaseContext databaseContext)
    {
        _databaseContext = databaseContext;
    }
    public IActionResult Index()
    {
        var user = _databaseContext.Users.ToList();
        return View();
    }
}

For more details about dependency injection, you can refer to this document.

  • Related