2016-11-22 80 views
2

数据库连接,我挣扎着找到资源,如何设置在ASP.net核心数据库连接字符串。我已经加入了连接字符串下面的appsettings.json文件:建立在.net中的核心应用

{ 
    "ConnectionStrings": { 
    "MTDatabase": "Server=ss-demo-7-sep112;Database=MTDB;Trusted_Connection=True;" 
    } 
} 

但需要找到一种方法,我在通用repositry访问此连接字符串。这是在一个单独的项目中找到我的.net核心应用程序,它包含所有数据访问层的东西。以下是我的通用储存库,我试图获取连接字符串

using System.Text; 
using System.Data.Entity; 
using System.Data.Entity.Infrastructure; 
using System.Configuration; 
using System.Data.Entity.Core.Objects; 

namespace HaldanMT.DAL 
{ 
    public class GenericRepository<T> : IDisposable, IRepository<T> where T : class, new() 
    { 

     protected ObjectContext _context; 
     protected ObjectSet<T> _objectSet { get; set; } 

     public GenericRepository(string connectionName = "MTDatabase") 
     { 
      _context = new ObjectContext(ConfigurationManager.ConnectionStrings[connectionName].ConnectionString); 
      _objectSet = _context.CreateObjectSet<T>(); 
     } 
    } 
} 

PS。我已经在我的.net核心项目中引用了这个DAL项目。尝试连接到数据库时项目失败,例外是System.NullReferenceException未将对象引用设置为对象的实例ConnectionString

任何帮助都非常感谢。

+0

您是否正在尝试设置EF6或EF Core?上面的代码看起来像ASP.NET 4.5/EF6。您是否也将.NET Core作为目标还是仅针对.NET Framework上的ASP.NET Core?它有很大的不同。 .NET Core和.NET Framework是运行时,ASP.NET Core只是一个webstack,它可以在两者上运行。然而,EF6只能在完整的.NET Framework上运行 – Tseng

回答