Search code examples
c#entity-frameworkgenericsn-tier-architecture

Getting an unexpected error with c# lazy loading in N-Tier design getting


My webapplication is designed after Implementing a generic data access layer using Entity Framework

I have to following code in my DAL for my Generic Repository loading:

public virtual IList<T> GetAll(params Expression<Func<T, object>>[] navigationProperties)
{
    List<T> list;
    using (var context = new Corporate_WebEntities())
    {
        IQueryable<T> dbQuery = context.Set<T>();
        foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
            dbQuery = dbQuery.Include<T, object>(navigationProperty);
        list = dbQuery
            .AsNoTracking()
            .ToList<T>();
    }
    return list;
}

and the following in my app.config file:

...
<connectionStrings>
    <add name="Corporate_WebEntities"
        connectionString="
            metadata=
                res://*/Model.csdl|
                res://*/Model.ssdl|
                res://*/Model.msl;
            provider=System.Data.SqlClient;
            provider connection string=&quot;
                data source=(local);
                initial catalog=Corporate_Web;
                persist security info=True;
                user id=*****;
                password=*****;
                MultipleActiveResultSets=True;
                App=EntityFramework&quot;"
        providerName="System.Data.EntityClient" />
</connectionStrings>
...

The error I am getting is:

No connection string named 'Corporate_WebEntities' could be found in the application config file.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: No connection string named 'Corporate_WebEntities' could be found in the application config file.

Source Error: 
Line 34:                    dbQuery = dbQuery.Include<T, object>(navigationProperty);
Line 35: 
Line 36:                list = dbQuery
Line 37:                    .AsNoTracking()
Line 38:                    .ToList<T>();

Source File: Z:\_Profile Storage\Projects\CorporateWeb.API\CorporateWeb.API.DAL\GenericDataRepository.cs    Line: 36 

Stack Trace: 
[InvalidOperationException: No connection string named 'Corporate_WebEntities' could be found in the application config file.]
   System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel() +288
   System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +466
   System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
   System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
   System.Data.Entity.Internal.Linq.InternalSet`1.AsNoTracking() +18
   System.Data.Entity.Infrastructure.DbQuery`1.AsNoTracking() +46
   System.Data.Entity.QueryableExtensions.AsNoTracking(IQueryable`1 source) +130
   CorporateWeb.API.DAL.GenericDataRepository`1.GetAll(Expression`1[] navigationProperties) in Z:\_Profile Storage\Projects\CorporateWeb.API\CorporateWeb.API.DAL\GenericDataRepository.cs:36
   CorporateWeb.API.BLL.BusinessLogicLayer_Settings.GetCompanyContactInformation() in Z:\_Profile Storage\Projects\CorporateWeb.API\CorporateWeb.API.BLL\BusinessLogicLayer_Settings.cs:375
   CorporateWeb.API.WebApiApplication.Session_Start() in Z:\_Profile Storage\Projects\CorporateWeb.API\CorporateWeb.API\Global.asax.cs:32

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
   System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) +0
   System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) +192
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +136
   System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) +21
   System.Web.Util.ArglessEventHandlerProxy.Callback(Object sender, EventArgs e) +56
   System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +9916528
   System.Web.SessionState.SessionStateModule.CompleteAcquireState() +160
   System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +1095
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +254
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

The thing I do not understand is that I have Corporate_WebEntities defined and the app compiles.

  1. What am I missing in my app.config?
  2. What other "things" am I missing?

Edit one My Model.Context.cs (where the Corporate_WebEntities is):

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace CorporateWeb.API.DAL
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using CorporateWeb.API.Model;

    public partial class Corporate_WebEntities : DbContext
    {
        public Corporate_WebEntities()
            : base("name=Corporate_WebEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Accounts> Accounts { get; set; }
        ...
    }
}

Solution

  • You are running a web application, put these connection strings in your WEB.CONFIG