Search code examples
c#asp.net-corerazorentity-framework-core

Why is my Dbconext SQL connection not working


I am fairly new to ASP.NET Core and have been using Entity Framework Core to work with SQL Server databases on my local machine. My most recent project is using .NET 7 runtime instead of 6 and the Web App Core template instead of the MVC one.

Here is the layout of my project so far.

Program.cs

using CommentsApplication.Db;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<DBconnection>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("localhost"));
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Dbconnection.cs

This is the DbContext that connects to my database. I have a single table in the database called accounts.

using CommentsApplication.Models;
using Microsoft.EntityFrameworkCore;

namespace CommentsApplication.Db
{
    public class DBconnection: DbContext
    {
        public DBconnection(DbContextOptions<DBconnection> options) : base(options) { }

        public DbSet<Account> accounts { get; set; }
    }
}

Here is what the Account class looks like

using System.ComponentModel.DataAnnotations;

namespace CommentsApplication.Models
{
    public class Account
    {
        [Key]
        public int Id { get; set; }
        public string Organization { get; set; }
        public string Email { get; set; }
    }
}

The connection string looks like this (my computers name is ZURG)

Server=ZURG;Database=AccountsDB;Trusted_Connection=True;Encrypt=False;

When I attempt to run the application I get this error:

InvalidOperationException: Unable to resolve service for type 'System.Data.Common.DbConnection' while attempting to activate 'CommentsApplication.Pages.IndexModel'.

This is what the IndexModel looks like:

using CommentsApplication.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Data.Common;

namespace CommentsApplication.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;

        private readonly DbConnection _db;

        public string org { get; set; }
        public string email { get; set; }

        public IndexModel(ILogger<IndexModel> logger, DbConnection DB)
        {
            _logger = logger;
            _db = DB;
        }

        public void OnGet()
        {
        }

        public void OnPost(string org, string email)
        {
            org = org.Trim();
            email = email.Trim();

            Account a = new Account()
                            { 
                                Organization= org, 
                                Email = email 
                            };
        }
    }
}

Every time I've used a similar setup in my other ASP.NET Core projects this has worked fine but for some reason this time it won't.

Is anyone able to point me in the right direction?


Solution

  • You messed up your naming... You called your DbContext "Dbconnection" note the lower case "c", but added a reference of type "DbConnection" so your viewmodel is looking for a System.Data.Common.DbConnection class.

    I'd recommend naming your DbContext something like "AppDbContext" to avoid naming confusion which will make case issues like this easier to spot/avoid.