0

I have my connection string to SQL stored in the Web project in appsettings.json

  "ConnectionStrings": {
    "MyDbConnectionString": "***"
  },

Then I added a DB context using Scaffold

Scaffold-DbContext -Connection "name=MyDbConnectionString" -Provider "Microsoft.EntityFrameworkCore.SqlServer"  ...  -Force

I can use the context in a controller and I have no issues getting data or writing. However, I would like all my business logic to be on a separate class library. So here is my repository from my Library:

    public class MyRepository
{

    private static MyContext CurrentContext
    {
        get { return new MyContext(); }
    }

    public static async void AddEventLog(EventLog eventLog)
    {
        using (var context = CurrentContext)
        {
            context.EventLog.Add(eventLog);
            await context.SaveChangesAsync();
        }
    }
}

But it fails when it tries to write to the DB.

System.InvalidOperationException: 'A named connection string was used, but the name 'MyDbConnectionString' was not found in the application's configuration.

Should I be adding appsettings.json to the library project (This seems redundant, and incorrect)? What am I missing? How do I reference back to the web projects appsettings.json file?

Any help would be greatly appreciated.

Here is my startup

services.AddDbContext<MyContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("MyDbConnectionString")));

1 Answer 1

0

***** HERE ARE CHANGES I HAVE MADE TO THE WORK *****

I have found the issue I believe so here we go.

  1. Remove the following from MySsdCaseContext.

    public MySsdCaseContext()
    {
    }
    

    and keep this one..

     public MySsdCaseContext(DbContextOptions<MySsdCaseContext> options) : base(options)
    {
    }
    
  2. For the purposes of fixing this comment out the following from OnConfiguring.

    if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer("name=MySsdCaseDb");
        }
    
  3. In startup.cs add the following inside ConfigureService method.

    services.AddDbContext<MySsdCaseContext>(options 
    =>options.UseSqlServer(Configuration.GetConnectionString("MySsdCaseDb")));
    

This should prompt you to add a reference to MySsdCase.Core.Data class library. You don't currently have this. Basically put the following at the top of startup.cs

    using MySsdCase.Core.Data;
  1. Ensure the following is inside MySsdCase.Web.cspoj

    <ItemGroup>
       <ProjectReference Include="..\MySsdCase.Core\MySsdCase.Core.csproj" />
    </ItemGroup>
    
  2. Do it like this...

          public class EventLogRepository 
        {
    private readonly MySsdCaseContext _context;
    
    public async Task AddEventLogAsync(EventLog eventLog)
    {
    
        var myVar = await _context.Set<ClientDetails>()
            .AsNoTracking()
            .Select(p => p)
            .Take(2)
            .ToListAsync();
    }
    }
    

I think overall there was no reference to the DAL from the BL in startup.cs.

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

3 Comments

I had AddDbContext in the startup and I did not post in my question. I edited my post and added. However, you recommended to use AddDbContextPool and I tried using that and I still get the same error. BTW.. The Connection string is working since I can use it from the controller. Error is just when I use it from the Class Library.
I have been struggling to figure this out for a while now... I believe I have narrowed down what I am looking for to be how do I pass the connection string thorough DI to my repository. I have tried the answer on this link: stackoverflow.com/questions/43058497/… but I am still having trouble.
Nevermind... In the index I was not passing the context in this call: _eventRepo = new EventLogRepository(context); @Bazza I really appreciate the help! Thanks Again!

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.