How to get data from my SQL Server database to my view in ASP.NET Core MVC web app

128 Views Asked by At

It's been a long time since I've had to get data from a SQL Server database to a view and so much has changed. I'm working on a new app and and have gone through the correct steps as far as I can see.

Define the model:

public class LoginModel
{
    public string UserId { get; set; } = null!;
    public string Username { get; set; } = null!;
    public string Password { get; set; } = null! ;
    public short UserType { get; set; }
}

Set up the DbContext:

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

    public virtual DbSet<LoginModel>? Login { get; set; }
}

Update the Program.cs:

builder.Services.AddDbContextFactory<WebContext>(
        opt => opt.UseSqlServer(
        builder.Configuration.GetConnectionString("WebConn")));

Update appsettings.json:

"ConnectionStrings": {
    "WebConn": "Data Source=LAPTOP-4LUQ899E;Initial 
        Catalog=BookSearch;TrustServerCertificate=Yes;Trusted_Connection=True"
},

So after all of this I expected to be able to access the data and filter it through to my View but not at all, when I run it, I get an error expecting to add a constructor in the context like below..

    public WebContext()
    {
    }

So I thought then I was oaky but now I get the error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider

This used to be a lot easier, where am I going wrong?

1

There are 1 best solutions below

2
Brando Zhang On

According to your codes, it worked at my side, I think the reason why you get the error is you may use the wrong code to active the WebContext.

The AddDbContextFactory method is different than the AddDbContext, if you are using the AddDbContext, you could just get the service directly by adding WebContext inside the constructor.

If you are using the AddDbContextFactory, you need create the dbcontext, more details,you could refer to below usage of it.

private readonly IDbContextFactory<WebContext> _contextFactory;

public ValuesController(IDbContextFactory<WebContext> contextFactory)
{
    _contextFactory = contextFactory;
}   

[HttpGet]
public async Task<IActionResult> Submit()
{
    using (var context = _contextFactory.CreateDbContext())
    {
  
        var result = context.Login.ToList();
    }
    return Ok("ss");
}

Result:

enter image description here

Besides, for how to use it, you could also refer to this article.


how do I use it with the following code to get data from the database. using (var context = new WebContext()) { var query = from st in context.Login select st; }

Firstly, as we use DI in asp.net core, there is no need for us to new a webcontext by ourselves.

Secondly, we have registered the AddDbContextFactory , this is used to create the WebContext. So if you want to get the data from database, you should firstly get the webcontext by using the DbContextFactory, then use created webcontext could get the data.

More details, you could refer to below codes:

    private readonly IDbContextFactory<WebContext> _contextFactory;

    public ValuesController(IDbContextFactory<WebContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }   

    [HttpGet]
    public async Task<IActionResult> Submit()
    {
        //this context is webcontext which created by the contextfactory, like var context = new WebContext() do 
        using (var context = _contextFactory.CreateDbContext())
        {
            var query = from st in context.Login select st;
            var result = context.Login.ToList();
        }
        return Ok("ss");
    }

Result2:

enter image description here