【问题标题】:Not able to access the connectionString无法访问连接字符串
【发布时间】:2019-05-22 20:43:56
【问题描述】:

我有一个解决方案,其中有两个项目,一个是主项目,另一个是用于实体框架的 classLibery 项目(因为我无法在 ASP.Net 核心项目中创建 ADO.Net 数据实体模型)我在主项目中添加了 ClassLibery 项目的引用并创建了它的一个对象,我能够访问实体模型的所有属性。但是当我运行代码时,我得到一个异常

"InvalidOperationException: 没有命名的连接字符串 'DefaultConnection' 可以在应用程序配置文件中找到。 System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()"

    <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SchoolMate.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
  </connectionStrings>

我在两个项目中都有相同的连接字符串。 我尝试了link 和许多其他链接中给出的解决方案,但没有一个可以提供帮助。

我的 HomeController,我在

处的 Index 方法中得到异常
var i = Model1Entities.Products.Where(x => x.ProductId==1);

这是我完整的家庭控制器

public class HomeController : Controller
{
    Entities Model1Entities;
    public HomeController()
    {
        Model1Entities = new Entities();
    }
    public IActionResult Index()
    {
        var i = Model1Entities.Products.Where(x => x.ProductId==1);
        return View();
    }
    }

【问题讨论】:

  • 很难找到解决方案。我们需要更多细节。可以分享代码吗?
  • 你需要哪部分代码??
  • 哪里出错了?您尝试访问连接字符串的位置
  • 分享您的Model1Entities 课程代码。
  • .net coreappsettings.json 文件中读取连接字符串。

标签: c# entity-framework-6


【解决方案1】:

请尝试以下方法:

在 DBContext 类中:

public partial class DefaultConnectionMapClass : DbContext
    {
        public DefaultConnectionMapClass(): base("name=DefaultConnection")
        {
            // Your code
        }
    }

【讨论】:

  • 感谢您的回答,但无法解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
相关资源
最近更新 更多