2017-11-07 2 views
-1

내가 뭘 잘못하고 있는지, 데이터베이스 프로젝트를 설정하기가 매우 어려워서 connectionstring dbcontext와 관련된 오류가 계속 발생합니다.ConnectionStrings EF 코어의 DbContext

난 그냥

문제가 내 데이터가 잘못된 위치에있을 것 같다 나는 그것을 해결하는 방법을 잘 모르겠습니다 어디 내 다른 dbcontext입니다 localdb에 연결되어 하나의 applicationdbcontext 있습니다. 이 코드는 startup.cs 내 모델 폴더

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

에 I가이 코드 .. services.AddDbContext (옵션 => options.UseSqlServer (Configuration.GetConnectionString ("DefaultConnection"))); services.AddDbContext (options => options.UseSqlServer (Configuration.GetConnectionString ("ProdConnection")))); 내 프로젝트를 실행할 때

내 appSettings는에

가이 코드를 config (설정) ..

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

아직 내가 실제로 구성을 사용하지 않을 공급되고 있다는 오류, 제어의 DI 반전을 얻을, 그 가방 고양이와 그것의 불!

+0

오류는 다음과 같습니다. AddDbContext가 구성과 함께 호출되었지만 'CustomerContext'컨텍스트 유형은 매개 변수없는 생성자 만 선언합니다. 즉, AddDbContext에 전달 된 구성은 절대로 사용되지 않습니다. 구성이 AddDbContext로 전달되면 'CustomerContext'는 DbContextOptions 를 허용하는 생성자를 선언하고 DbContext의 기본 생성자에 전달해야합니다. 그래서 더 이상 작동하지 않는 onConfiguring을 수집합니다. 어떻게 수정해야합니까? . – webdev8183

+0

ugh 분명히 그것은 startup.cs 파일의 문자열을 전혀 필요로하지 않았지만, 잘 구성한 설정에서 덮어 쓰기를 수행했지만 바보 같았고 동일한 연결 문자열을 두 번 사용하려고했습니다. – webdev8183

답변

0

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 개의 별개의 장소에서의 연결. 그리고 나는 예외를 던졌다라고 생각한다.

+0

: base (options) 아니 op는 아무것도하지 않지만 구현이없는 기본 클래스를 호출합니다. 연결 문자열은 필요하지 않습니다. 두 번 사용하면 되겠지만 지금은 입력 해 주셔서 감사합니다. – webdev8183

+0

당신은 use services.AddDbContext (options => options.UseSqlServer (Configuration.GetConnectionString ("DefaultConnection")));을 사용한다고 말합니다. start.cs에서. 이 연결 문자열 옵션 매개 변수는 db 컨텍스트 생성자에서 허용되어야합니다. –

+0

아니요 시작시 생성자에서 연결을 정의했습니다. 인수없이 전달했으며 작동했습니다. – webdev8183

관련 문제