0
votes

I don't know what I am doing wrong, trying very hard to setup a database project, and keep getting errors related to the connectionstring dbcontext.

I have one applicationdbcontext which is just connecting to localdb

the problem is my other dbcontext which is where my data is seems to be in the wrong place and I am not sure how to fix it. This code is in my models folder

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

in startup.cs I have this code.. services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("ProdConnection")));

in my appsettings config I have this code..

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

yet when I run my project I get an error that the configuration being supplied is not being used,DI inversion of control indeed, its a bag of cats and its on fire!

1
Error is like this-- AddDbContext was called with configuration, but the context type 'CustomerContext' only declares a parameterless constructor. This means that the configuration passed to AddDbContext will never be used. If configuration is passed to AddDbContext, then 'CustomerContext' should declare a constructor that accepts a DbContextOptions<CustomerContext> and must pass it to the base constructor for DbContext so I gather overriding onConfiguring no longer works, how do I fix it, someone please help. - webdev8183
ugh apparently it didn't need the string in the startup.cs file at all, it took the override from onconfiguring just fine, but then it was stupid and wanted to use the same connection string twice.. - webdev8183

1 Answers

0
votes

You should remove the optionsBuilder.UseSqlServer("... line in your OnConfiguring method.

Then add a constructor to your DbContext class like this;

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

Adding DbContext class..

 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 class..

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

Anyways its working now, my mistake was that I had defined the connection in 2 seperate places and I guess that threw an exception.