【问题标题】:Cannot add DbContext ASP.Net Core or access data using controllers无法添加 DbContext ASP.Net Core 或使用控制器访问数据
【发布时间】:2018-05-12 16:31:41
【问题描述】:

我使用 Scaffold-DbContext 创建了一个上下文

Scaffold-DbContext "Server=******.database.windows.net;Database=first_choice_main; User ID = ****; Password=****" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models\Azure\Main

它在 Models\Azure\Main 文件夹中创建了以下上下文:

namespace firstChoicePortal.Models.Azure.Main
{
    public partial class First_choice_mainContext : DbContext
    {
        public virtual DbSet<BlobsDetails> BlobsDetails { get; set; }
        public virtual DbSet<BranchInfo> BranchInfo { get; set; }
        public virtual DbSet<BranchMatrix> BranchMatrix { get; set; }
        public virtual DbSet<CommEventLog> CommEventLog { get; set; }
        public virtual DbSet<CommEventTypes> CommEventTypes { get; set; }
        public virtual DbSet<ContainerEvents> ContainerEvents { get; set; }
        public virtual DbSet<ContainerEventTypes> ContainerEventTypes { get; set; }
        public virtual DbSet<Containers> Containers { get; set; }
        public virtual DbSet<ContainerScans> ContainerScans { get; set; }
        public virtual DbSet<Customers> Customers { get; set; }
        public virtual DbSet<Drivers> Drivers { get; set; }
        public virtual DbSet<ExcludedPoints> ExcludedPoints { get; set; }
        public virtual DbSet<FilesToFtp> FilesToFtp { get; set; }
        public virtual DbSet<FtpEventLog> FtpEventLog { get; set; }
        public virtual DbSet<IncomingTngReturnScans> IncomingTngReturnScans { get; set; }
        public virtual DbSet<ItemTypes> ItemTypes { get; set; }
        public virtual DbSet<LinehaulTracker> LinehaulTracker { get; set; }
        public virtual DbSet<MaintEventTypes> MaintEventTypes { get; set; }
        public virtual DbSet<NewgisticsScans> NewgisticsScans { get; set; }
        public virtual DbSet<OutgoingUpdateQueue> OutgoingUpdateQueue { get; set; }
        public virtual DbSet<PodDetail> PodDetail { get; set; }
        public virtual DbSet<PodUpdatesSentDetail> PodUpdatesSentDetail { get; set; }
        public virtual DbSet<PodUpdatesSentMaster> PodUpdatesSentMaster { get; set; }
        public virtual DbSet<PointMaintEvents> PointMaintEvents { get; set; }
        public virtual DbSet<ProgramSettings> ProgramSettings { get; set; }
        public virtual DbSet<ReceiveScanEventTypes> ReceiveScanEventTypes { get; set; }
        public virtual DbSet<ReceiveScanLog> ReceiveScanLog { get; set; }
        public virtual DbSet<ReceiveScans> ReceiveScans { get; set; }
        public virtual DbSet<RepAssignedStopMatrix> RepAssignedStopMatrix { get; set; }
        public virtual DbSet<RepInfo> RepInfo { get; set; }
        public virtual DbSet<ScanTypes> ScanTypes { get; set; }
        public virtual DbSet<StopAddressDetails> StopAddressDetails { get; set; }
        public virtual DbSet<StopEventLog> StopEventLog { get; set; }
        public virtual DbSet<StopEventTypes> StopEventTypes { get; set; }
        public virtual DbSet<SystemsConfiguration> SystemsConfiguration { get; set; }
        public virtual DbSet<Table> Table { get; set; }
        public virtual DbSet<TestData> TestData { get; set; }
        public virtual DbSet<TestLh> TestLh { get; set; }
        public virtual DbSet<TngRmaItems> TngRmaItems { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer(@"Server=*****.database.windows.net;Database=first_choice_main; User ID = *****; Password=*****");
            }
        }

然后我使用右键单击方法并选择“API Controller with actions, using EF”创建了一个控制器。

这是它的第一部分:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using firstChoicePortal.Models.Azure.Main;

namespace firstChoicePortal.Controllers
{
    [Produces("application/json")]
    [Route("api/RepInfoApi")]
    public class RepInfoApiController : Controller
    {
        private readonly First_choice_mainContext _context;

        public RepInfoApiController(First_choice_mainContext context)
        {
            _context = context;
        }

        // GET: api/RepInfoApi
        [HttpGet]
        public IEnumerable<RepInfo> GetRepInfo()
        {
            return _context.RepInfo;
        }

如果我运行它并转到 https://localhost:44325/api/RepInfoApi 我得到:

InvalidOperationException:尝试激活“firstChoicePortal.Controllers.RepInfoApiController”时,无法解析“firstChoicePortal.Models.Azure.Main.First_choice_mainContext”类型的服务。

所以我想也许我需要在启动时将其添加到我的服务中,我补充说:

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

但我现在在启动时遇到运行时错误:

"System.ArgumentException: 'AddDbContext 是通过配置调用的,但是上下文类型 'First_choice_mainContext' 只声明了一个无参数的构造函数。这意味着永远不会使用传递给 AddDbContext 的配置。如果将配置传递给 AddDbContext,那么 ' First_choice_mainContext' 应该声明一个接受 DbContextOptions&lt;First_choice_mainContext&gt; 的构造函数,并且必须将其传递给 DbContext 的基本构造函数。'"

我是不是走错路了?

解决方案的更新和说明

我有几件事丢失/错误,正如 Nkosi 指出的那样,错误消息确实包含解决方案。但它比这更深一些。我试图做的是使用从 appsettings.json 文件中提取的连接字符串。该工具可以 100% 正常工作,但它使用以下代码直接在数据上下文中硬编码您的连接信息:

 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
                optionsBuilder.UseSqlServer(@"Server=******.database.windows.net;Database=first_choice_main; User ID = ******; Password=******");
            }
        }

如您所见,MS 建议删除此代码并将其替换为基于连接字符串的解决方案——我几乎做到了。差点没把它剪掉——再次感谢 SO 社区!

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc


    【解决方案1】:

    异常消息清楚地说明了您需要做什么

    'AddDbContext 是通过配置调用的,但上下文类型 'First_choice_mainContext' 仅声明了一个无参数构造函数。这意味着传递给 AddDbContext 的配置将永远不会被使用。 如果将配置传递给 AddDbContext,则“First_choice_mainContext”应声明一个接受 DbContextOptions&lt;First_choice_mainContext&gt; 的构造函数,并且必须将其传递给 DbContext 的基本构造函数

    强调我的

    按照说明添加构造函数

    public partial class First_choice_mainContext : DbContext {
    
    
        public First_choice_mainContext(DbContextOptions<First_choice_mainContext> options) 
            : base(options) {
        }
    
        //...
    }
    

    这样在注入依赖类时可以正确解析上下文。

    【讨论】:

    • 谢谢 - 我会接受这个答案,因为它 100% 解决了问题。我不明白为什么默认工具没有/没有创建这个?我应该用我的 Scaffold-DbContext 命令做些什么不同的事情吗?我不记得必须手动修改我之前创建的上下文,但我之前一直在使用 Postgresql vs sql server。
    • OK...我很困惑为什么工具没有首先创建这个。我将更新我的问题以反映我所学到的东西,以防其他人绊倒。
    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2018-03-24
    • 2021-01-06
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多