5

我已經開發了asp.net核心wep api 2.0應用程序與EntityFrameworkCore.SqlServer 2.0。它是使用數據庫第一種方法開發的。當試圖使用dbcontext訪問實體應用程序將打破模式。我無法找到應用程序狀態進入中斷狀態的原因。請幫助解決這個問題。應用程序中斷訪問dbcontext,Asp .net核心web api 2.0與實體框架核心2.0數據庫第一種方法

以下是DBContext類中的OnConfiguring方法。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     if (!optionsBuilder.IsConfigured) 
     { 
      optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;"); 
     } 
    } 

下面的代碼塊用於訪問控制的DbContext實體

// GET api/values 
    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     VotingAppDBContext context = new VotingAppDBContext(); 
     var questions = context.Questions.ToList(); 
     return new string[] { "value1", "value2" }; 
    } 

Installed packages

Application error

+0

我有確切的問題。我不知道如何解決它迄今。 – hidden

+0

所以......你的數據庫有模式嗎?當我刪除我的模式,然後腳手架開始工作。 – hidden

+0

我發現我的問題。我用VARCHAR(max)來定義列的長度。通常EF不理解,並且默默地失敗 – hidden

回答

1

1.-首先你不應該建立在控制器內部上下文,避免在依賴項中使用'new',因爲這會使你的代碼無法測試,在我使用UnitOfWork的情況下,我將它注入爲IUnitOfWork instan ce,這的確是MyConext的擴展,並且你會在StartUp類中注入它...爲此,我有一個私有方法(在單個私人調用中執行此操作):

private void AddEntityFrameworkAndDbContext(IServiceCollection services) { services.AddEntityFrameworkSqlServer();

 var migrationsAssemblyName = typeof(MyContext).GetTypeInfo().Assembly.GetName().Name; 
     services.AddDbContext<MyContext>(options => 
     { 
      options.UseSqlServer(
       "MY CONNECTION STRING GOES HERE (BUT I RETREIVE IT FROM ANOTHER SERVICE)", 
       sqlServerOptionsAction: sqlOptions => 
       { 
        sqlOptions.MigrationsAssembly(migrationsAssemblyName); 
        sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); 
       }); 
     }, 
     ServiceLifetime.Scoped // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request) 
       ).AddUnitOfWork<MyContext>(); // This is because I'm also using EF Core Unit of work NuGet Package 
    } 

我打電話,從ConfigureServices(IServiceCollection服務),正如我所說,在啓動類

 // Add EF, and UoW 
     AddEntityFrameworkAndDbContext(services); 

2:二(私有方法,但我想說,這是你的真正的問題)我想說,你錯過了base.OnConfiguring(選項);在你的情況下,它應該是這樣的:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 
    { 
     if (!optionsBuilder.IsConfigured) 
     { 
      optionsBuilder.UseSqlServer(@"Server=(local);Database=VotingAppDB;User ID=sa;Password=123;"); 
     } 
     base.OnConfiguring(optionsBuilder); 
    } 

另外,請看一看這個答案我幾周前寫道: How to setup EF6 Migrations with ASP.NET Core

此外,的UnitOfWork項目值得一讀,取看看這裏:https://github.com/arch/UnitOfWork

我希望它能幫助,

胡安

0

不河畔e如果問題仍然存在。今天我有同樣的問題。解決的辦法是更新所有nuget包(在我的情況下,Microsoft.Extensions.Configuration等)到最新版本。

+0

就我而言,這是由於自引用主鍵。當我刪除該參考時,它工作。 –

-1

當您在模式中自引用主鍵時會發生這種情況。使用sql server數據庫圖表可以以圖形方式查看。您必須刪除該參考才能解決此問題。

相關問題