在N层设计获取中,c#lazy加载出现意外错误

本文关键字:加载 c#lazy 错误 意外 获取 | 更新日期: 2023-09-27 18:25:51

我的Web应用程序是在使用实体框架实现通用数据访问层之后设计的

我必须在我的DAL中为我的通用存储库加载以下代码:

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;
}

以及我的app.config文件中的以下内容:

...
<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>
...

我得到的错误是:

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

我不明白的是,我已经定义了Corporate_WebEntities,并且应用程序正在编译。

  1. app.config中缺少什么
  2. 我还缺少什么"东西"

编辑一个My Model.Context.cs(其中Corporate_WebEntities):

//------------------------------------------------------------------------------
// <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; }
        ...
    }
}

在N层设计获取中,c#lazy加载出现意外错误

如果正在运行web应用程序,请将这些连接字符串放入WEB.CONFIG