【问题标题】:Unable to resolve service for type for DbContext generated from Scaffold-DbContext and Scaffolded Razor Pages using Entity Framework (CRUD)无法解析使用实体框架 (CRUD) 从 Scaffold-DbContext 和 Scaffolded Razor 页面生成的 DbContext 类型的服务
【发布时间】:2021-02-26 22:46:50
【问题描述】:

我正在尝试使用数据库优先方法和剃须刀页面脚手架。

第 1 步。我在包管理控制台中运行

Scaffold-DbContext 'MyConnectionStringInfo' Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force

这会按预期为每个表生成模型,以及 LoanCalculatorDBContext.cs。

第 2 步。我在 Pages 文件夹中创建了一个名为“LoanEstimateRequests”的文件夹
第 3 步。我右键单击文件夹并添加新的脚手架项目“使用实体框架 (CRUD) 的脚手架 Razor 页面”。

  • 模型类:LoanEstimateRequest
  • 数据上下文类:LoanCalculatorDBContext(在步骤 1 中创建的)

第 4 步。然后我运行应用程序,并导航到 /loanestimaterequests,这会导致以下错误:

处理请求时发生未处理的异常。 InvalidOperationException:无法解析类型的服务 'LoanCalculator.Models.LoanCalculatorDBContext' 尝试 激活“LoanCalculator.Pages.LoanEstimateRequests.IndexModel”。

如何解决此错误?还是我应该使用不同的方法?
LoanCalculatorDBContext.cs

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

#nullable disable

namespace LoanCalculator.Models
{
    public partial class LoanCalculatorDBContext : DbContext
    {
        public LoanCalculatorDBContext()
        {
        }

        public LoanCalculatorDBContext(DbContextOptions<LoanCalculatorDBContext> options)
            : base(options)
        {
        }

        public virtual DbSet<CreditScore> CreditScores { get; set; }
        public virtual DbSet<LoanEstimateRequest> LoanEstimateRequests { get; set; }
        public virtual DbSet<LoanOfficer> LoanOfficers { get; set; }
        public virtual DbSet<LoanType> LoanTypes { get; set; }
        public virtual DbSet<PurchaseOrRefinance> PurchaseOrRefinances { get; set; }
        public virtual DbSet<State> States { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("MyConnectionInfo");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<CreditScore>(entity =>
            {
                entity.ToTable("CreditScore");

                entity.Property(e => e.DisplayName)
                    .IsRequired()
                    .HasMaxLength(25);
            });

            modelBuilder.Entity<LoanEstimateRequest>(entity =>
            {
                entity.ToTable("LoanEstimateRequest");

                entity.Property(e => e.AddressLine1)
                    .IsRequired()
                    .HasMaxLength(100)
                    .IsFixedLength(true);

                entity.Property(e => e.AddressLine2)
                    .HasMaxLength(100)
                    .IsFixedLength(true);

                entity.Property(e => e.City)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsFixedLength(true);

                entity.Property(e => e.Email)
                    .IsRequired()
                    .HasMaxLength(100);

                entity.Property(e => e.FirstName)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.LastName)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.Zip)
                    .IsRequired()
                    .HasMaxLength(5)
                    .IsUnicode(false)
                    .HasColumnName("ZIP")
                    .IsFixedLength(true);

                entity.HasOne(d => d.CreditScoreNavigation)
                    .WithMany(p => p.LoanEstimateRequests)
                    .HasForeignKey(d => d.CreditScore)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_LoanEstimateRequest_CreditScore");

                entity.HasOne(d => d.LoanOfficerNavigation)
                    .WithMany(p => p.LoanEstimateRequests)
                    .HasForeignKey(d => d.LoanOfficer)
                    .HasConstraintName("FK_LoanEstimateRequest_LoanOfficer");

                entity.HasOne(d => d.LoanTypeNavigation)
                    .WithMany(p => p.LoanEstimateRequests)
                    .HasForeignKey(d => d.LoanType)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_LoanEstimateRequest_LoanType");

                entity.HasOne(d => d.PurchaseOrRefinanceNavigation)
                    .WithMany(p => p.LoanEstimateRequests)
                    .HasForeignKey(d => d.PurchaseOrRefinance)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_LoanEstimateRequest_PurchaseOrRefinance");

                entity.HasOne(d => d.StateNavigation)
                    .WithMany(p => p.LoanEstimateRequests)
                    .HasForeignKey(d => d.State)
                    .OnDelete(DeleteBehavior.ClientSetNull)
                    .HasConstraintName("FK_LoanEstimateRequest_State");
            });

            modelBuilder.Entity<LoanOfficer>(entity =>
            {
                entity.ToTable("LoanOfficer");

                entity.Property(e => e.FirstName)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.LastName)
                    .IsRequired()
                    .HasMaxLength(50);

                entity.Property(e => e.Nmlsnumber)
                    .IsRequired()
                    .HasMaxLength(50)
                    .HasColumnName("NMLSNumber");
            });

            modelBuilder.Entity<LoanType>(entity =>
            {
                entity.ToTable("LoanType");

                entity.Property(e => e.DisplayName)
                    .IsRequired()
                    .HasMaxLength(50);
            });

            modelBuilder.Entity<PurchaseOrRefinance>(entity =>
            {
                entity.ToTable("PurchaseOrRefinance");

                entity.Property(e => e.DisplayName)
                    .IsRequired()
                    .HasMaxLength(50);
            });

            modelBuilder.Entity<State>(entity =>
            {
                entity.ToTable("State");

                entity.Property(e => e.Abbreviation)
                    .IsRequired()
                    .HasMaxLength(2)
                    .IsUnicode(false)
                    .IsFixedLength(true);

                entity.Property(e => e.DisplayName)
                    .IsRequired()
                    .HasMaxLength(50)
                    .IsUnicode(false)
                    .IsFixedLength(true);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

索引.cshtml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using LoanCalculator.Models;

namespace LoanCalculator.Pages.LoanEstimateRequests
{
    public class IndexModel : PageModel
    {
        private readonly LoanCalculator.Models.LoanCalculatorDBContext _context;

        public IndexModel(LoanCalculator.Models.LoanCalculatorDBContext context)
        {
            _context = context;
        }

        public IList<LoanEstimateRequest> LoanEstimateRequest { get;set; }

        public async Task OnGetAsync()
        {
            LoanEstimateRequest = await _context.LoanEstimateRequests
                .Include(l => l.CreditScoreNavigation)
                .Include(l => l.LoanOfficerNavigation)
                .Include(l => l.LoanTypeNavigation)
                .Include(l => l.PurchaseOrRefinanceNavigation)
                .Include(l => l.StateNavigation).ToListAsync();
        }
    }
}

启动.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using LoanCalculator.Data;

namespace LoanCalculator
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
//This was added in another iteration when I had set the Scaffolding Entity Framework CRUD operation to create a new DBContext
            services.AddDbContext<LoanCalculatorContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("LoanCalculatorContext")));

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                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.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

【问题讨论】:

  • 请显示您的启动文件。
  • 添加了 Startup.cs

标签: asp.net-core entity-framework-core razor-pages


【解决方案1】:

我没有看到你的控制器类。你如何开始你的应用程序。 如果是 MVC 应用程序,最好使用 Index 视图和 HomeController 以及 Index 操作 你的配置服务应该是这样的:

public void ConfigureServices(IServiceCollection services)
    {
        
            services.AddControllersWithViews()
    .AddNewtonsoftJson(options =>
           options.SerializerSettings.ContractResolver =
              new CamelCasePropertyNamesContractResolver());
              
              services.AddDbContext<LoanCalculatorContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("LoanCalculatorContext")));
  }

并用此代码替换您的 UserEndpoints

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");

            });

用此代码替换 LoanCalculatorDBContext 的 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 方法

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                
            }
        }

【讨论】:

  • 感谢您的建议,您能澄清一下吗?我将把代码 sn-p 放在哪个文件中,里面有什么?
  • 我按照您的说明操作并收到以下错误:处理请求时发生未处理的异常。 InvalidOperationException:尝试激活“LoanCalculator.Pages.LoanEstimateRequests.IndexModel”时无法解析“LoanCalculator.Models.LoanCalculatorDBContext”类型的服务。 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型 requiredBy,bool isDefaultParameterRequired)。 if 里面什么都没有是故意的吗?这似乎与我最初遇到的错误相同。
  • 我没有看到你的控制器类。你如何开始你的应用程序。您应该拥有 Index 视图和 HomeController 以及 Index 操作
  • 这是一个剃须刀页面应用而不是 mvc。
  • 对不起,如果您不使用 mvc,我根本不明白它是如何工作的。并且您将问题标记为 asp.net-core。您可以使用带有 mvc 的 pazor 页面甚至网络表单。正如我在回答中所示,您必须将代码更改为使用 mvc。我认为将任何内容放在一页中没有任何意义。你只是在找麻烦。
【解决方案2】:

由于您使用的是DB First,所以dbcontext 配置是在OnConfiguring 方法中设置的。

但在 .NET Core 应用程序中,配置更有可能通过 ServiceCollection 的 AddDbContext 扩展方法放在 Startup 类中:

services.AddDbContext<LoanCalculatorContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("LoanCalculatorContext")));

就像你在上面所做的一样,你需要在 appsettings.json 中存储连接字符串:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "LoanCalculatorContext": "MyConnectionInfo"
  }
}

MyConnectionInfo 与 LoanCalculatorDBContext OnConfiguring 方法中的相同。

【讨论】:

    猜你喜欢
    • 2022-06-21
    • 1970-01-01
    • 2012-05-30
    • 2018-05-22
    • 2015-11-10
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多