无法访问connectionString

时间:2019-05-22 11:48:07

标签: c# entity-framework-6

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

  

“ 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();
    }
    }

2 个答案:

答案 0 :(得分:0)

请尝试以下操作:

在DBContext类中:

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

答案 1 :(得分:0)

您可能已经检查了类库项目中的app.config,并且实际上存在连接字符串。不知何故,这是行不通的。

您必须将该连接字符串移动到启动项目。现在再试一次。

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Test.webapp.mdf;Initial Catalog=aspnet-Test.webapp;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>