简体   繁体   English

无法创建对象上下文

[英]Unable to create object context

I'm getting the Unable to create object context error when using Entity framework in ASP.NET MVC.在 ASP.NET MVC 中使用实体框架时出现Unable to create object context错误。

Background背景

Every time I POST to the controller I'm not getting a response back.每次我POST到控制器时,我都没有得到回复。 I tried going directly to the method of the controller /Data/GetAll , and receive this error:我尝试直接转到控制器/Data/GetAll ,并收到此错误:

Error错误

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.指定的命名连接在配置中找不到,不打算与 EntityClient 提供程序一起使用,或者无效。 Description: An unhandled exception occurred during the execution of the current web request.说明:在执行当前 Web 请求期间发生未处理的异常。 Please review the stack trace for more information about the error and where it originated in the code.请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。

Exception Details: System.ArgumentException: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.异常详细信息: System.ArgumentException:在配置中找不到指定的命名连接,不打算与 EntityClient 提供程序一起使用,或者无效。

Code Snippet that throws exception:抛出异常的代码片段:

public class TrackItContextCreator {
    public ObjectContext Create() {
        ObjectContext context = new ObjectContext("name=TrackItDBEntities");

        context.DefaultContainerName = "TrackItDBEntities";

        return context;
    }
}

Web.config网页配置

<add name="TrackItDBEntities" connectionString="metadata=res://*
/EntityFramework.TrackItDBModel.csdl|res://*/EntityFramework.TrackItDBModel.ssdl|res:
//*/EntityFramework.TrackItDBModel.msl;provider=System.Data.SqlClient;provider
 connection string=&quot;Data Source=host;User ID=myuseracc;Password=******;
MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient" />

What could I be missing?我可能会错过什么?

From the comments, I think I know what the problem is.从评论中,我想我知道问题是什么。

If the model is in a separate assembly, you basically have to make sure that the connection string is specified in the app.config / web.config of every assembly that uses the model.如果模型在单独的程序集中,您基本上必须确保在使用该模型的每个程序集的app.config / web.config中指定连接字符串。 I'm guessing that you only have it in the model project.我猜你只在模型项目中拥有它。

See this question for another example, and this thread on MSDN .有关另一个示例,请参阅此问题,以及MSDN 上的此线程 Both similar issues involving models being in separate projects/assemblies.两个类似的问题都涉及模型在不同的项目/组件中。 I'm 99% sure that this is related to your issue.我 99% 确定这与您的问题有关。

如果您使用类库开发 Web 应用程序,您应该将数据库的 connectionStrings 添加到 Web.Config 和 App.Config。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM