Search code examples
c#.net-4.0

I am having this error: System.InvalidOperationException: 'No connection string named 'CashinEntities' could be found in the application config file


My project used to have a 3-tier architecture, namely UI, Application, and Data. However, I added one more tier - API. Previously, my application connected to the data layer and still does so without any problems. But with the new change, I passed the responsibilities of reading and writing to the database to my data layer through repositories. For some reason, my application layer still connects to the database, but my repositories in the data layer do not, and it gets the error "System.InvalidOperationException: 'No connection string named 'CashinEntities' could be found in the application config file." described above! I do have a web.config file in my UI application as suggested by many in other posts. My project is EF database first in .net 4.7

MY CashinModel.Context.cs

namespace cashin.data
{
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    
    public partial class CashinEntities : DbContext
    {
        public CashinEntities()
            : base("name=CashinEntities")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
     }
 }

MY ClienteRepository.cs

public class ClienteRepository : IClienteRepository
    {
        private readonly CashinEntities _context;

        public ClienteRepository()
        {
            _context = new CashinEntities();
        }
        
        public async Task<bool> InsertClienteAsync(CSH_Cliente cliente)
        {
            try
            {
                _context.CSH_Cliente.Add(cliente);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error inserting client: {ex.Message}");
                return false;
            }
        }
    }

IN MY Application Layer (where it is working) i connect to the same CashinModel.Context.cs using this connectio class:

public class App
{
    public CashinEntities db = new CashinEntities();

    public class AppResultado
    {
        public bool Exito { get; set; } = false;
        public string Mensagem { get; set; } = "mensagem";
        public object Objeto { get; set; }
        public AppResultado Good(string msg)
        {
            this.Exito = true;
            this.Mensagem = msg;
            return this;
        }
        public AppResultado Bad(string msg)
        {
            this.Exito = false;
            this.Mensagem = msg;
            return this;
        }
    }
}

MY App.Config

<configuration>
   <connectionStrings>
    <add name="CashinEntities" connectionString="metadata=res://*/CashinModel.csdl|res://*/CashinModel.ssdl|res://*/CashinModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=HAH;initial catalog=Cashin;persist security info=True;user id=sa;password=band;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
</configuration>

Solution

  • After facing some challenges with "No connection string named 'CashinEntities' could be found in the application config file", I followed these steps to get everything working correctly:

    1 - Connection String in web.config:

    I moved the connection string to the web.config file inside my Web API project, instead of the UI project.

    2 - Install Unity Container:

    I installed the Unity.Container package in the API project references.

    3 - Create UnityConfig File:

    I created a UnityConfig configuration file with the following code:

    public static class UnityConfig { private static Lazy container = new Lazy(() => { var container = new UnityContainer(); RegisterTypes(container); return container; });

    public static IUnityContainer Container => container.Value;
    
    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterType<DbContext, CashinEntities>();
    
        // Register Repository
    } }
    

    This file connects to my DbContext in the data layer.

    4 - Register Container in Global.asax:

    I registered the container in the Global.asax file inside the Application_Start method:

    protected void Application_Start() { var container = DependencyConfig.RegisterDependencies();

    GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    
    GlobalConfiguration.Configure(config => WebApiConfig.Register(config, container));
    
    // Default ASP.NET MVC setup }
    

    By following these steps, I was able to solve "No connection string named 'CashinEntities' could be found in the application config file" which resided in the my Data Layer, and I could ensure my Web API project could use the DbContext from the data layer and find the connection string.

    Thank you Guru Stron and T McKeown for trying to help, I appreciate.