【问题标题】:ConnectionStrings DbContext in EF CoreEF Core 中的 ConnectionStrings DbContext
【发布时间】:2018-04-19 20:56:16
【问题描述】:

我不知道自己做错了什么,非常努力地设置数据库项目,并不断收到与连接字符串 dbcontext 相关的错误。

我有一个刚刚连接到 localdb 的 applicationdbcontext

问题是我的另一个 dbcontext,我的数据似乎在错误的位置,我不知道如何修复它。此代码在我的模型文件夹中

public DbSet<Customer> Customers { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Staff> Staff { get; set; }
public DbSet<RequestType> RequestType { get; set; }
public DbSet<CustomerJob> CustomerJobs { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;");
}

在 startup.cs 我有这个代码.. services.AddDbContext(选项 => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext(选项 => options.UseSqlServer(Configuration.GetConnectionString("ProdConnection")));

在我的 appsettings 配置中,我有这个代码..

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=BRSCRM;Trusted_Connection=True;MultipleActiveResultSets=true",
    "ProdConnection": "Server=(localdb\\mssqllocaldb;Database=Customers;Trusted_Connection=True;MultipleActiveResults=true"
},

然而,当我运行我的项目时,我得到一个错误,提供的配置没有被使用,DI 控制反转确实,它是一袋猫,它着火了!

【问题讨论】:

  • 错误是这样的-- AddDbContext 是用配置调用的,但是上下文类型'CustomerContext'只声明了一个无参数的构造函数。这意味着永远不会使用传递给 AddDbContext 的配置。如果将配置传递给 AddDbContext,则“CustomerContext”应声明一个接受 DbContextOptions 的构造函数,并且必须将其传递给 DbContext 的基本构造函数,因此我收集到覆盖 onConfiguring 不再有效,我该如何修复它,请有人帮忙.
  • 呃显然它根本不需要 startup.cs 文件中的字符串,它从 onconfiguring 中进行了覆盖就好了,但是它很愚蠢,想使用相同的连接字符串两次。 .

标签: asp.net entity-framework asp.net-core-mvc


【解决方案1】:

您应该删除OnConfiguring 方法中的optionsBuilder.UseSqlServer("... 行。

然后像这样向你的 DbContext 类添加一个构造函数;

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

添加 DbContext 类..

 public class CustomerContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public DbSet<Job> Jobs { get; set; }
    public DbSet<Order> Orders { get; set; }
    public DbSet<Staff> Staff { get; set; }
    public DbSet<RequestType> RequestType { get; set; }
    public DbSet<CustomerJob> CustomerJobs { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Customers;Trusted_Connection=True;");
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //modelBuilder.Entity<CustomerJob>()
        //    .HasKey(c => new { c.JobId, c.CustomerId });
        //code to require a staff member be assigned..

       // modelBuilder.Entity<Staff>().Property(s => s.Name).IsRequired();
        //  modelBuilder.Entity<Customer>().Property(c => c.AssignedStaff).IsRequired();
    }


}


public class CustomerJob
{
    public int CustomerJobId { get; set; }
    public int CustomerId { get; set; }
    public DateTime RequestDate { get; set; }
    public int JobId { get; set; }
    public Job Job { get; set; }
}

public class Job
{
    public int JobId { get; set; }
    public int CustomerId { get; set; }

    public string BusinessName { get; set; }
    public string Name { get; set; }
    public string JobDescription { get; set; }
    public string ServiceType { get; set; }
    public string GoogleLink { get; set; }
    public string PoisLink { get; set; }
    public bool EquisRendered { get; set; }
    public bool NadirsRemoved { get; set; }
    public string FolderLink { get; set; }
    public string ReviewPosted { get; set; }
    public string Ingestion { get; set; }
    public string Moderated { get; set; }
    public bool Delivered { get; set; }
    public string CustomerReview { get; set; }
    public string PublishedLink { get; set; }
    public DateTime RequestDate { get; set; }
    public DateTime LastModifiedDate { get; set; }
    public DateTime ScheduleShootDate { get; set; }
    public DateTime CompletionDate { get; set; }
    public List<CustomerJob> CustomerJobs { get; set; }
    public Staff AssignedStaff { get; set; }
}

public class Staff
{
    public int StaffId { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
    public string EMail { get; set; }
}

public class Order
{
    public int OrderID { get; set; }
    public int CustomerID { get; set; }
    public int Order_Detail_Id { get; set; }
    public List<Job> Job { get; set; }
}

public class RequestType
{
    public int ID { get; set; }
    public string Description { get; set; }
}

}

Startup.cs 类..

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.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddDbContext<CustomerContext>();

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();
        // Add Oauth Options 
        /* Third Party Login Authenticaton Options Google */
        services.AddAuthentication().AddGoogle(googleOptions =>
        {
            googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
            googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
        });
        /* End Google Options */
        /* Begin Facebook Options  */
        services.AddAuthentication().AddFacebook(facebookOptions =>
        {
            facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
            facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
        });

        /* End Facebook Options  */

        /* Begin Microsoft Options */
        services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
        {
            microsoftOptions.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
            microsoftOptions.ClientSecret = Configuration["Authentication:Microsoft:Password"];
        });

        /* End Microsoft Options  */

        /* Twitter Options  */
        services.AddAuthentication().AddTwitter(twitterOptions =>
        {
            twitterOptions.ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"];
            twitterOptions.ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"];
        });
        /* End Twitter Options */
        /* Begin Identity Options Configuration   */
        services.AddMvc();
        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
        });
    }

无论如何它现在可以工作,我的错误是我在 2 个单独的地方定义了连接,我猜这引发了异常。

【讨论】:

  • :base(options) 是一个无操作,除了调用没有实现的基类,它什么也不做,连接字符串是需要的,只是不需要两次让它现在工作,但感谢输入。
  • 你说使用 services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));在你的 startup.cs 中。此连接字符串选项参数必须在您的数据库上下文构造函数中接受。
  • 不,我在启动 cs 的构造函数中定义了连接,我不带参数传递它并且它工作。
  • 你能添加你的dbcontext和startup.cs的完整代码吗?
  • 我尝试在我的原始帖子上,不确定它是否允许发布那么长的帖子,无论如何我让它工作了。我将尝试编辑我的原始帖子以包含这些内容。我了解到,当您通过覆盖 OnConfiguring 方法定义上下文文件时,您实际上可以添加连接字符串,该方法来自 Julie Lerman 教授的关于复数视觉的课程(她是世界上最重要的实体框架权威之一。)
猜你喜欢
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-02
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
相关资源
最近更新 更多