2

I'm battling to find resources on how to setup a database connection string in ASP.net core. I have added the connection string to the appsettings.json file below:

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

but need to find a way to access this connection string in my generic repositry. which is found in a seperate project to my .net core app where it contains all Data Access Layer stuff. Below is my generic repositry where I am trying to get my connection string

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. I have already made reference to this DAL project in my .net core project. The project fails when trying to connect to the DB, the exception is System.NullReferenceException Object reference not set to an instance of an object for the ConnectionString

Any help is greatly appreciated.

1
  • Are you trying to set up EF6 or EF Core? The above code looks like ASP.NET 4.5 / EF6. also do you target .NET Core or just ASP.NET Core on full .NET Framework? Its a huge difference. .NET Core and .NET Framework are runtimes, ASP.NET Core is just a webstack, which runs on both. EF6 however only runs on full .NET Framework Commented Nov 22, 2016 at 7:04

1 Answer 1

2

https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro

This is the link where the use of JSON as connection string is mentioned. it will be like this

Configuration.GetConnectionString("ConnectionStrings")).

Just follow the tutorial will help you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.