2016-12-07 60 views
1

我有一個在.NET Framework 4.6.1中作爲項目運行的EntityFramework 6的DAL。適用於其他.NET Framework項目的解決方案。現在我要使用引用到我的ASP.NET Core WebApi(使用.NET Framework 4.6.1)的相同DAL項目,並且它不起作用。例外情況如下:如何從被引用的.NET Framework項目中的appsettings.json中獲取設置

在應用程序配置文件中找不到名爲'MyEntities'的連接字符串。

.NET核心項目不具有web.config文件,所以EF6我如何將設置從我的Core項目中的appsettings.json傳遞到引用的DAL項目?

我發現了一些例子,讓EF6在.NET Core項目(如https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6)中工作,但它並沒有幫助我。我想這是因爲dbcontext是在DAL項目中創建的。

appsettings.json

"ConnectionStrings": { 
    "MyEntities": "<my connectionString>" 
}, 

project.json

"dependencies": { 
    "EntityFramework": "6.1.3", 
    ... 
}, 
... 
"frameworks": { 
    "net461": { 
    "dependencies": { 
     "DAL": { 
     "target": "project" 
     } 
    }, 
    "imports": "dnxcore50" 
    } 
}, 

回答

1

嗯..我沒有得到我想要的答案。所以我做了一個解決方法,我不得不改變DAL項目中的一些代碼。希望它不會破壞其他項目的某些功能......

在DAL項目中:
由於我首先使用Model的EF實體,因此無法更改模型。但是它創建了部分類,因此我使用帶參數的contstructor爲MyEntity創建了另一個部分類。

namespace DAL.Models 
{ 
    public partial class MyEntities 
    { 
     public MyEntities(string connString) : base(connString) 
     { 
     } 
    } 
} 

而在DAL回購我創建了一個構造函數參數(從我的.NET核心項目注入)和私人方法。

public class UserRepository : IUserRepository 
{ 
    private readonly string _dbContextString; 

    public UserRepository(string dbContextString) 
    { 
     _dbContextString = dbContextString; 
    } 

    private MyEntities GetMyEntities() 
    { 
     return string.IsNullOrEmpty(_dbContextString) ? new MyEntities() : new MyEntities(_dbContextString); 
    } 
    ... 
} 

然後我做了搜索和替換myEntity所()的用途,從

using (var context = new MyEntities()) 
    { 
     ... 

using (var context = GetMyEntities()) 
    { 
     ... 

在我的.NET的核心項目:
在啓動。 cs我在ConfigureService中添加了一行以在我的repo中注入connectionString。

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddMvc(); 

    services.AddSingleton<IUserRepository>(new UserRepository(Configuration.GetConnectionString("MyEntities"))); 
    ... 

田田,現在它與我的新的.NET核心項目一起工作,仍然與其他.NET框架項目一起工作!

0

你必須注入所需控制器爲IConfiguration並把它傳遞到達爾項目

//dependency inject it in required controller or service class 
    IConfiguration Config 
//this will get your connection string 
    Config.GetSection("ConnectionStrings").GetSection("MyEntities") 
+0

我不知道如何把這個在我的控制器。我應該如何初始化'Config',以及如何將它傳遞給DAL項目? –

+0

我找到了一個[answer](http://stackoverflow.com/a/40902384),我可以使用它將連接字符串傳遞給項目。但這不是我的解決方案,因此DAL被其他項目使用,我無法改變處理來自他們的呼叫的方式。 我希望我可以讓我的appsettings.json令人放心。網絡解決方案中的項目。 –

+0

使您的DAL項目接受連接字符串作爲靜態屬性或構造函數參數。然後從將使用DAL項目的項目傳遞連接字符串。 – Sriram

相關問題