无法添加DbContext ASP.Net Core或使用控制器访问数据

时间:2018-05-12 16:31:41

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

我使用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 文件夹中创建了以下Context:

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=*****");
            }
        }

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

这是它的第一部分:

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:无法解析类型&#39; firstChoicePortal.Models.Azure.Main.First_choice_mainContext&#39;试图激活&#39; firstChoicePortal.Controllers.RepInfoApiController&#39;。

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

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

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

  

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

我是以错误的方式解决这个问题吗?

解决方案的更新和解释

我有一些遗漏/错误,并且正如Nkosi指出错误消息确实包含解决方案。但它比这更深刻。我试图做的是使用从appsettings.json文件中提取的连接字符串。工具100%工作,但它使用这段代码直接在datacontext中硬编码你的连接信息:

 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社区!

1 个答案:

答案 0 :(得分:2)

异常消息明确说明您需要做什么

  

'使用配置调用AddDbContext,但上下文类型'First_choice_mainContext'仅声明无参数构造函数。这意味着永远不会使用传递给AddDbContext的配置。 如果配置传递给AddDbContext,那么'First_choice_mainContext'应该声明一个接受Auth::user()->address()->create($request->all()); 的构造函数,并且必须将它传递给DbContext的基础构造函数

强调我的

按照说明添加构造函数

DbContextOptions<First_choice_mainContext>

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