突然,在实例化生成的ObjectContext类时,我一直得到一个MetadataException。App.Config中的连接字符串看起来是正确的-自从上次它工作以来没有改变-我已经尝试从底层数据库中重新生成一个没有变化的新模型(edmx-file)。

有人有什么想法吗?

进一步的细节:我没有更改任何属性,没有更改任何输出程序集的名称,也没有尝试将EDMX嵌入到程序集中。我只是下班后等了10个小时才回来。然后它就不管用了。

我试过重新创造EDMX。我试着重新创建这个项目。我甚至尝试从头开始重新创建数据库。不管怎样,运气不好。


当前回答

我编写了这个helper类,当ObjectContext对象定义在与使用它的项目不同的项目中时,它可以创建对象的实例。我解析配置文件中的连接字符串,并将'*'替换为完整的程序集名称。

它并不完美,因为它使用反射来构建对象,但这是我能找到的最通用的方法。

希望它能帮助到别人。

public static class EntityHelper<T> where T : ObjectContext
{
    public static T CreateInstance()
    {
        // get the connection string from config file
        string connectionString = ConfigurationManager.ConnectionStrings[typeof(T).Name].ConnectionString;

        // parse the connection string
        var csBuilder = new EntityConnectionStringBuilder(connectionString);

        // replace * by the full name of the containing assembly
        csBuilder.Metadata = csBuilder.Metadata.Replace(
            "res://*/",
            string.Format("res://{0}/", typeof(T).Assembly.FullName));

        // return the object
        return Activator.CreateInstance(typeof(T), csBuilder.ToString()) as T;
    }
}

其他回答

在我的情况下,列出的答案没有一个是有效的,所以我发布了这个。

For my case, building on Visual studio and running it with IIS express worked fine. But when I was deploying using Nant scripts as a stand-alone website was giving errors. I tried all the suggestions above and then realized the DLL that was generated by the nant script was much smaller than the one generated by VS. And then I realized that Nant was unable to find the .csdl, .msl and .ssdl files. So then there are really two ways to solve this issue, one is to copy the needed files after visual studio generates them and include these files in the build deployment. And then in Web.config, specify path as:

"metadata=~/bin/MyDbContext.csdl|~/bin/MyDbContext.ssdl|~/bin/MyDbContext.msl;provider=System.Data.SqlClient;...."

这是假设您已经手动复制文件到您正在运行的网站的bin目录。如果它在不同的目录中,则相应地修改path。 第二种方法是在Nant脚本中执行EdmGen.exe,并生成文件,然后将它们作为资源,如下例所示: https://github.com/qwer/budget/blob/master/nant.build

我也遇到了和Rick一样的问题和解决方案,只是我要将一个现有的.edmx导入到一个新项目中,虽然基本名称空间无关紧要,但它被导入到不同的子目录中,因此我还必须更新Web内部的连接字符串。配置在三个地方,包括不同的子目录命名:

我刚花了30分钟玩这个。我重命名了实体对象,重命名了配置文件中的条目,但还有更多…您还必须更改对CSDL的引用

很容易错过-如果您正在重命名,请确保您获得所有内容....

这发生在我身上,当我不小心切换了edmx文件的构建动作(出现在IDE属性下)从“EntityDeploy”到“None”。EntityDeploy为您填充元数据:请参阅http://msdn.microsoft.com/en-us/library/cc982037.aspx

我能够在Visual Studio 2010, VB.net (ASP.NET) 4.0中解决这个问题。

在实体模型向导期间,您将能够看到实体连接字符串。从这里,您可以复制并粘贴到连接字符串中。

我唯一缺少的是连接字符串中的“App_Code.”。

entityBuilder.Metadata = "res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl"