简体   繁体   English

MetadataException:无法加载指定的元数据资源

[英]MetadataException: Unable to load the specified metadata resource

All of a sudden I keep getting a MetadataException on instantiating my generated ObjectContext class. The connection string in App.Config looks correct - hasn't changed since last it worked - and I've tried regenerating a new model (edmx-file) from the underlying database with no change.突然间,我在实例化生成的ObjectContext class 时不断收到MetadataException中的连接字符串看起来正确 - 自上次工作以来没有改变 - 我尝试从底层数据库没有变化。

Anyone have any ideas?谁有想法?

Further details: I haven't changed any properties, I haven't changed the name of any output assemblies, I haven't tried to embed the EDMX in the assembly.更多详细信息:我没有更改任何属性,我没有更改任何 output 程序集的名称,我没有尝试将 EDMX 嵌入程序集中。 I've merely waited 10 hours from leaving work until I got back.从下班到回来,我只等了 10 个小时。 And then it wasn't working anymore.然后它不再工作了。

I've tried recreating the EDMX.我试过重新创建 EDMX。 I've tried recreating the project.我试过重新创建项目。 I've even tried recreating the database, from scratch.我什至尝试过从头开始重新创建数据库。 No luck, whatsoever.没有运气,无论如何。

This means that the application is unable to load the EDMX.这意味着应用程序无法加载 EDMX。 There are several things which can cause this.有几件事会导致这种情况。

  • You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory.您可能已将模型的 MetadataArtifactProcessing 属性更改为复制到输出目录。
  • The connection string could be wrong.连接字符串可能是错误的。 I know you say you haven't changed it, but if you have changed other things (say, the name of an assembly), it could still be wrong.我知道您说您没有更改它,但是如果您更改了其他内容(例如,程序集的名称),它仍然可能是错误的。
  • You might be using a post-compile task to embed the EDMX in the assembly, which is no longer working for some reason.您可能正在使用后编译任务将 EDMX 嵌入程序集中,但由于某种原因它不再工作。

In short, there is not really enough detail in your question to give an accurate answer, but hopefully these ideas should get you on the right track.简而言之,您的问题中没有足够的细节来给出准确的答案,但希望这些想法能让您走上正轨。

Update: I've written a blog post with more complete steps for troubleshooting .更新:我写了一篇博客文章,其中包含更完整的故障排除步骤

A minor amendment helped me with this problem.一个小的修改帮助我解决了这个问题。

I had a solution with 3 project references:我有一个包含 3 个项目参考的解决方案:

connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl;

which I changed to:我改为:

connectionString="metadata=res://*/;

You can get this exception when the Edmx is in one project and you are using it from another.当 Edmx 在一个项目中并且您从另一个项目中使用它时,您可能会遇到此异常。

The reason is Res://*/ is a uri which points to resources in the CURRENT assembly.原因是Res://*/是一个指向 CURRENT 程序集中资源的 uri。 If the Edm is defined in a different assembly from the code which is using it, res://*/ is not going to work because the resource cannot be found.如果 Edm 是在与使用它的代码不同的程序集中定义的,则 res://*/ 将无法工作,因为找不到资源。

Instead of specifying '*', you need to provide the full name of the assembly instead (including public key token).您需要提供程序集的全名(包括公钥令牌),而不是指定“*”。 Eg:例如:

res://YourDataAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdefabcedf/YourEdmxFileName.csdl|res://...

A better way to construct connection strings is with EntityConnectionStringBuilder:构造连接字符串的更好方法是使用 EntityConnectionStringBuilder:

public static string GetSqlCeConnectionString(string fileName)
{
    var csBuilder = new EntityConnectionStringBuilder();

    csBuilder.Provider = "System.Data.SqlServerCe.3.5";
    csBuilder.ProviderConnectionString = string.Format("Data Source={0};", fileName);

    csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl", 
        typeof(YourObjectContextType).Assembly.FullName);

    return csBuilder.ToString();
}

public static string GetSqlConnectionString(string serverName, string databaseName)
{
    SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();

    providerCs.DataSource = serverName;
    providerCs.InitialCatalog = databaseName;
    providerCs.IntegratedSecurity = true;

    var csBuilder = new EntityConnectionStringBuilder();

    csBuilder.Provider = "System.Data.SqlClient";
    csBuilder.ProviderConnectionString = providerCs.ToString();

    csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
        typeof(YourObjectContextType).Assembly.FullName);

    return csBuilder.ToString();
}

If you still encounter the exception, open the assembly in reflector and check the filenames for your .csdl, .ssdl and .msl files.如果仍然遇到异常,请在反射器中打开程序集并检查 .csdl、.ssdl 和 .msl 文件的文件名。 When the resources have different names to the ones specified in the metadata value, it's not going to work.当资源的名称与元数据值中指定的名称不同时,它将不起作用。

I had a similar error.我有一个类似的错误。 I had recreated the project (long story), and pulled everything over from the old project.我重新创建了这个项目(长篇大论),并从旧项目中提取了所有内容。 I hadn't realized that my model had been in a directory called 'Model' before, and was now in a directory called 'Models'.我之前没有意识到我的模型在一个名为“Model”的目录中,现在在一个名为“Models”的目录中。 Once I changed the connection in my Web.Config from this:一旦我从这里更改了我的 Web.Config 中的连接:

<add name="RecipeManagerEntities" connectionString="metadata=res://*/Model.Recipe.csdl 

to this:对此:

<add name="RecipeManagerEntities" connectionString="metadata=res://*/Models.Recipe.csdl

Everything worked (changed Model to Models ).一切正常(将Model更改为Models )。 Note that I had to change this three places in this string.请注意,我必须更改此字符串中的这三个位置。

And a quick way to check the model name without Reflector.... look for the directory还有一种快速检查没有反射器的模型名称的方法....查找目录

...obj/{config output}/edmxResourcesToEmbed ...obj/{配置输出}/edmxResourcesToEmbed

and check that the .csdl, .msl, and .ssdl resource files are there.并检查 .csdl、.msl 和 .ssdl 资源文件是否存在。 If they are in a sub-directory, the name of the sub-directory must be prepended to the model name.如果它们位于子目录中,则子目录的名称必须添加到模型名称之前。

For example, my three resource files are in a sub-directory Data , so my connection string had to be例如,我的三个资源文件位于子目录Data中,所以我的连接字符串必须是

metadata=res://*/ Data .MyModel.csdl|res://*/ Data .MyModel.ssdl|res://*/ Data .MyModel.msl; metadata=res://*/数据.MyModel.csdl|res://*/数据.MyModel.ssdl|res://*/数据.MyModel.msl;

(versus metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;). (相对于元数据=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;)。

I also had this problem and it was because the connectionstring in my web.config was slightly different than the one in the app.config of the assembly where my EDMX is located.我也遇到了这个问题,这是因为我的 web.config 中的连接字符串与我的 EDMX 所在程序集的 app.config 中的连接字符串略有不同。 No idea why it changed, but here are the two different versions.不知道为什么会改变,但这里有两个不同的版本。

App.config:应用程序配置:

<add name="SCMSEntities" connectionString="metadata=res://*/Model.SMCSModel.csdl|res://*/Model.SMCSModel.ssdl|res://*/Model.SMCSModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" />

Web.config:网络配置:

<add name="SCMSEntities" connectionString="metadata=res://*/Model.SCMSModel.csdl|res://*/Model.SCMSModel.ssdl|res://*/Model.SCMSModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

What fixed it was simply copying the app.config string (notice the small difference at the end - instead of " App=EntityFramework " it wanted " application name=EntityFramework ") into the web.config and problem was solved.解决它的方法是简单地将 app.config 字符串(注意末尾的细微差别 - 而不是“ App=EntityFramework ”它想要“ application name=EntityFramework ”)复制到 web.config 中,问题就解决了。 :) :)

This happens to me when I do not clean solution before build new .edmx designer.当我在构建新的 .edmx 设计器之前不清理解决方案时,就会发生这种情况。 So just don't forget to clean solution before you build new .edmx designer.因此,在构建新的 .edmx 设计器之前不要忘记清理解决方案。 This helps me to skip lot more issues with this one.这有助于我跳过这个问题的更多问题。 Bellow the navigation details provided incase you are new in visual studio.如果您是 Visual Studio 的新手,请在下方提供导航详细信息。

Click->Build->Clean Solution点击->构建->清理解决方案

Then Click->Build->Rebuild Solution然后点击->构建->重建解决方案

Hope this helps.希望这可以帮助。 Thanks everyone感谢大家

This happened to me when I accidentally switched the Build Action of the edmx file (appears under Properties in the IDE) from 'EntityDeploy' to 'None'.当我不小心将 edmx 文件的构建操作(出现在 IDE 的属性下)从“EntityDeploy”切换到“None”时,这发生在我身上。 EntityDeploy is what populates the metadata for you: see http://msdn.microsoft.com/en-us/library/cc982037.aspx EntityDeploy 为您填充元数据:请参阅http://msdn.microsoft.com/en-us/library/cc982037.aspx

If you are using the edmx from a different project, then in the connection string, change...如果您使用的是来自不同项目的 edmx,则在连接字符串中,更改...

metadata=res://*/Data.DataModel.csdl

...to... ...至...

metadata=res://*/DataModel.csdl

I've just spent a happy 30 minutes with this.我刚刚度过了愉快的 30 分钟。 I'd renamed the entities object, renamed the entry in the config file, but there's more ... you have to change the reference to the csdl as well我重命名了实体对象,重命名了配置文件中的条目,但还有更多......您还必须更改对 csdl 的引用

very easy to miss - if you're renaming, make sure you get everything ....很容易错过 - 如果你要重命名,请确保你得到了一切......

I had the same problem.我有同样的问题。 I looked into my complied dll with reflector and have seen that the name of the resource was not right.我用反射器查看了我编译的 dll,发现资源的名称不正确。 I renamed and it looks fine now.我重命名了,现在看起来很好。

For my case, it is solved by changing the properties of edmx file.就我而言,它是通过更改 edmx 文件的属性来解决的。

  1. Open the edmx file打开.edmx文件
  2. Right click on any place of the EDMX designer右键单击 EDMX 设计器的任意位置
  3. choose properties选择属性
  4. update Property called "Metadata Artifact Processing" to "Embed in Output Assembly"将名为“元数据工件处理”的属性更新为“嵌入输出程序集”

this solved the problem for me.这为我解决了问题。 The problem is, when the container try to find the meta data, it cant find it.问题是,当容器试图找到元数据时,它找不到它。 so simply make it in the same assembly.所以只需在同一个程序集中进行即可。 this solution will not work if you have your edmx files in another assembly如果您的 edmx 文件位于另一个程序集中,此解决方案将不起作用

I spent a whole day on this error我花了一整天的时间来解决这个错误

if you are working with n-tear architecture如果您正在使用n-tear architecture

or you tried to separate Models generated by EDMX form DataAccessLayer to DomainModelLayer或者您尝试将EDMX生成的separate ModelsDomainModelLayer

maybe you will get this error也许你会得到这个错误

  1. First troubleshooting step is to make sure the Connection string in webconfig (UILayer) and appconfig (DataAccessLayer) are the same第一个故障排除步骤是确保webconfig (UILayer)appconfig (DataAccessLayer)中的连接字符串相同
  2. Second which is Very important the connection string第二个非常重要的connection string

     connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provid.....

    which is the problem这是问题所在

from where on earth I got Model or whatever .csdl in my connection string where are they我从地球上的哪里得到Model或连接字符串中的任何 .csdl 它们在哪里

here I our solution look at the picture这里我我们的解决方案看图

在此处输入图像描述

hope the help you希望对你有帮助

Sometimes i see this error in my project.有时我会在我的项目中看到这个错误。 I solve that by我解决了这个问题

1 - Right click on EDMX file 1 - 右键单击​​ EDMX 文件

2 - Select Run Custom Tool option 2 - 选择Run Custom Tool选项

3 - Rebuild project 3 - 重建项目

After hours of googling and trying to solve none of the solutions suggested worked.经过数小时的谷歌搜索并试图解决建议的解决方案都没有奏效。 I have listed several solution here.我在这里列出了几个解决方案。 I have also noted the one that worked for me.我还注意到对我有用的那个。 (I was using EF version 6.1.1, and SQL server 2014 - but an older DB) (我使用的是 EF 版本 6.1.1 和 SQL Server 2014 - 但使用的是较旧的数据库)

  1. Rebuilding the project and try again.重建项目并重试。
  2. Close and open VS - I don't know how this works关闭并打开 VS - 我不知道这是如何工作的
  3. make sure if you have placed the .EDMX file inside a Directory, make sure you include the Directories in your ConnectionString.确保您已将 .EDMX 文件放置在目录中,并确保将目录包含在您的 ConnectionString 中。 for example mine is inside DAL folder.例如我的在 DAL 文件夹中。 SO it looks like this: connectionString="metadata=res://*/DAL.nameModel.csdl|res://*/DAL.nameModel.ssdl|res://*/DAL.nameModel.msl; (these are files. to see them you can toggle Show All Files in solution explorer, under ~/obj/.. directory)所以它看起来像这样: connectionString="metadata=res://*/DAL.nameModel.csdl|res://*/DAL.nameModel.ssdl|res://*/DAL.nameModel.msl; (这些是文件。要查看它们,您可以在 ~/obj/.. 目录下的解决方案资源管理器中切换显示所有文件)

...and many more which I had tried [like: reverting the EntityFramework version to a later version(not sure about it)] ...以及我尝试过的更多[例如:将 EntityFramework 版本恢复到更高版本(不确定)]


what worked for me:什么对我有用:

from this article here , it helped me solve my problem.从这里的这篇文章,它帮助我解决了我的问题。 I just changed my ProviderManifestToken="2012" to ProviderManifestToken="2008" in the EDMX file.我刚刚在 EDMX 文件中将ProviderManifestToken="2012"更改为ProviderManifestToken="2008" To do this:去做这个:

Solution Explorer解决方案资源管理器

  1. Right click over file .edmx右键单击文件 .edmx
  2. Open with..打开用..
  3. Editor XML编辑器 XML
  4. Change ProviderManifestToken="XXXX" with 2008将 ProviderManifestToken="XXXX" 更改为 2008

I hope that helps.我希望这会有所帮助。

I was able to resolve this in Visual Studio 2010, VB.net (ASP.NET) 4.0.我能够在 Visual Studio 2010、VB.net (ASP.NET) 4.0 中解决这个问题。

During the entity model wizard, you will be able to see the entity connection string.在实体模型向导期间,您将能够看到实体连接字符串。 From there you can copy and paste into your connection string.从那里您可以复制并粘贴到您的连接字符串中。

The only thing I was missing was the "App_Code."我唯一缺少的是“App_Code”。 in the connections string.在连接字符串中。

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

My issue and solution, the symptoms were the same "Unable to load the specified metadata resource" but the root cause was different.我的问题和解决方案,症状是相同的“无法加载指定的元数据资源”,但根本原因不同。 I had 2 projects in solution one was the EntityModel and the other the solution.我在解决方案中有 2 个项目,一个是 EntityModel,另一个是解决方案。 I actually deleted and recreated the EDMX file in the EntityModel.我实际上在 EntityModel 中删除并重新创建了 EDMX 文件。

The solution was that I had to go back to the Web Application project and add this line into the config file.解决方案是我必须回到 Web 应用程序项目并将这一行添加到配置文件中。 The new model had changed a few items which had to be duplicated in the "other" project's Web.Config file.新模型更改了一些必须在“其他”项目的 Web.Config 文件中复制的项目。 The old configuration was no longer good.旧配置不再好。

     <add name="MyEntities"
     connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;
                    provider=System.Data.SqlClient;
                    provider connection string=&quot;
                    data source=Q\DEV15;initial catalog=whatever;
                    user id=myuserid;password=mypassword;
                    multipleactiveresultsets=True;
                    application name=EntityFramework&quot;"
     providerName="System.Data.EntityClient" />

In my case, this issue was related to renaming my model's edmx file... correcting the app.config connection string for the csdl/ssdl/msl files fixed my issue.就我而言,此问题与重命名模型的 edmx 文件有关...更正 csdl/ssdl/msl 文件的 app.config 连接字符串解决了我的问题。

If you're using the EF 4.0 designer to generate your csdl/ssdl/msl, these 3 "files" will actually be stored within the model's main edmx file.如果您使用 EF 4.0 设计器生成 csdl/ssdl/msl,这 3 个“文件”实际上将存储在模型的主 edmx 文件中。 In this case, the post by Waqas is pretty much on the mark.在这种情况下,Waqas 的帖子非常符合要求。 It's important to understand that "Model_Name" in his example will need to be changed to whatever the current name of your model's .edmx file (without the .edmx).重要的是要理解他的示例中的“Model_Name”需要更改为模型的 .edmx 文件的当前名称(没有 .edmx)。

Also, if your edmx file is not at the root level of your project, you need to preface Model_Name with the relative path, eg此外,如果您的 edmx 文件不在项目的根级别,您需要在 Model_Name 前面加上相对路径,例如

res://*/MyModel.WidgetModel.csdl|res://*/MyModel.WidgetModel.ssdl|res://*/MyModel.WidgetModel.msl

would specify the csdl/ssdl/msl xml is stored in the model file 'WidgetModel.edmx' which is stored in a folder named 'MyModel'.将指定 csdl/ssdl/msl xml 存储在模型文件“WidgetModel.edmx”中,该文件存储在名为“MyModel”的文件夹中。

The ultimate solution (even after recreating the database on two other machines, as well as the EDMX and other sundries) was to not use the first edition of Entity Framework.最终的解决方案(即使在另外两台机器上重新创建数据库,以及 EDMX 和其他杂项)是不使用实体框架的第一版。 Looking forward to evaluating it again in .NET 4.0.期待在 .NET 4.0 中再次对其进行评估。

After running into the same problem again and searching all over for an answer, I finally found someone who'd had the same problem.再次遇到同样的问题并到处寻找答案后,我终于找到了遇到同样问题的人。 It appears that the connection string wasn't correctly generated by Visual Studio's wizard, and the link to the metadata resources was missing an important path.似乎 Visual Studio 的向导未正确生成连接字符串,并且元数据资源的链接缺少重要路径。

v1.0 BUG?: Unable to load the specified metadata resource. v1.0 BUG?:无法加载指定的元数据资源。 Scripts != Models脚本 != 模型

Update 2013-01-16 : Having transitioned to almost exclusively using EF Code First practices (even with existing databases) this problem is no longer an issue. 2013-01-16 更新:已经过渡到几乎完全使用 EF Code First 实践(即使使用现有数据库),这个问题不再是问题。 For me, that was a viable solution to reducing the clutter from auto-generated code and configuration and increasing my own control over the product.对我来说,这是一个可行的解决方案,可以减少自动生成的代码和配置造成的混乱,并增加我自己对产品的控制。

I have written this helper class to create instances of ObjectContext objects when they are defined in a different project than the project using it.当 ObjectContext 对象在与使用它的项目不同的项目中定义时,我编写了这个帮助类来创建 ObjectContext 对象的实例。 I parse the connection string in the config file and replace '*' by the full assembly name.我解析配置文件中的连接字符串并用完整的程序集名称替换“*”。

It is not perfect because it uses reflection to build the object, but it is the most generic way of doing it that I could find.它并不完美,因为它使用反射来构建对象,但它是我能找到的最通用的方法。

Hope it helps someone.希望它可以帮助某人。

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 all of you SelftrackingEntities Users , if you have followed the Microsoft Walk-through and separated the Object context class into the wcf service project (by linking to the context .tt) so this answer is for you :对于所有SelftrackingEntities用户,如果您遵循 Microsoft 演练并将 Object 上下文类分离到 wcf 服务项目中(通过链接到上下文 .tt),那么这个答案适合您:

part of the shown answers in this post that includes code like :这篇文章中显示的部分答案包括如下代码:

... = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl", 
        typeof(YourObjectContextType).Assembly.FullName); 

WILL NOT WORK FOR YOU !!不会为你工作! the reason is that YourObjectContextType.Assembly now resides in a different Assembley (inside the wcf project assembly) ,原因是YourObjectContextType.Assembly现在驻留在不同的 Assembley 中(在 wcf 项目程序集中),

So you should replace YourObjectContextType.Assembly.FullName with -->所以你应该用 --> 替换YourObjectContextType.Assembly.FullName

ClassTypeThatResidesInEdmProject.Assembly.FullName 

have fun.玩得开心。

例外是因为编译器指向不存在的元数据,所以只需将app.config连接字符串复制到Web.config连接字符串

With having same problem I re-created edmx from Database.遇到同样的问题,我从数据库重新创建了 edmx。 Solves my problem.解决了我的问题。

I was having problems with this same error message.我遇到了同样的错误消息。 My issue was resolved by closing and re-opening Visual Studio 2010.我的问题通过关闭并重新打开 Visual Studio 2010 得到解决。

Had same issue because I renamed an assembly.有同样的问题,因为我重命名了一个程序集。

I had to also rename it in AssemblyTitle and AssemblyProduct attributes in project Properties/AssemblyInfo.cs, and also deleting and re adding the reference to the edmx file.我还必须在项目 Properties/AssemblyInfo.cs 中的 AssemblyTitle 和 AssemblyProduct 属性中重命名它,并删除并重新添加对 edmx 文件的引用。

Then it worked just fine.然后它工作得很好。

As for me, I had separated Data Access Layer and User Interface layer.至于我,我已经分离了数据访问层和用户界面层。 So I have entity connection string for each layer.所以我有每一层的实体连接字符串。

Before I modify these two separated connection strings to be the same, I still found that below error.在我将这两个单独的连接字符串修改为相同之前,我仍然发现以下错误。

Unable to load the specified metadata resource

So I make to be the same connection strings for those two layers (DAL , UI), It work perfect.所以我为这两层(DAL,UI)设置了相同的连接字符串,它工作得很好。

My solution is to make all connection string to be the same no matter where they already presented .我的解决方案是使所有连接字符串都相同,无论它们已经出现在哪里

我也有与 Rick 相同的问题和解决方案,除了我将现有的 .edmx 导入到新项目中,虽然基本命名空间无关紧要,但它被导入到不同的子目录中,所以我还必须更新连接Web.Config 中三个位置的字符串,以包含不同的子目录命名:

I had this problem yesterday and was looking at my code in debug and the output from SQL Profiler.我昨天遇到了这个问题,正在调试中查看我的代码和 SQL Profiler 的输出。

What I couldn't understand, before I read and understood this post, was why EntityFramework was throwing this error as it was calling the DB.在我阅读并理解这篇文章之前,我无法理解的是,为什么 EntityFramework 在调用数据库时会抛出这个错误。 I was looking through hundreds of lines in SQL Profiler trying to work out what was wrong with the database model.我正在查看 SQL Profiler 中的数百行代码,试图找出数据库模型出了什么问题。 I couldn't find anything like the call I was expecting, and to be honest I wasn't certain what I was looking for.我找不到任何像我期待的电话一样的东西,老实说,我不确定我在寻找什么。

If you are in this position, check the connection string.如果您处于此位置,请检查连接字符串。 My guess is that before EntityFramework creates its SQL it will check the model, specified in the metadata part of the connection string.我的猜测是,在 EntityFramework 创建其 SQL 之前,它会检查模型,在连接字符串的元数据部分中指定。 In my case it was wrong.就我而言,这是错误的。 EntityFramework wasn't even making it as far as the DB. EntityFramework 甚至没有达到数据库。

Make sure the names are correct.确保名称正确。 Once I got that sorted out, I was then seeing calls in SQL Profiler where the ApplicationName was 'EntityFramework' with SQL calling the expected tables.一旦我把它整理好,我就会在 SQL Profiler 中看到调用,其中 ApplicationName 是“EntityFramework”,而 SQL 调用了预期的表。

A poor app.config or web.config file can do this.. I had copied the app.config connection string to my web.config in my UI and ended up entering:一个糟糕的 app.config 或 web.config 文件可以做到这一点。我已将 app.config 连接字符串复制到我的 UI 中的 web.config 并最终输入:

<connectionStrings>
    <connectionStrings>
          <add name="name" connectionString="normalDetails"/>
    </connectionStrings>
</connectionStrings>

我只是没有引用包含 EDMX 文件的类库。

Using the info from this blogpost :使用此博文中的信息:

Like others have said, res:\\ is a pointer to your resources.就像其他人所说的那样, res:\\ 是指向您的资源的指针。 To check and make sure your resource names are correct you can use a decompiler like DotPeek by JetBrains to open up your .dll file and see your Resources files.要检查并确保您的资源名称正确,您可以使用像JetBrains 的 DotPeek这样的反编译器来打开您的 .dll 文件并查看您的资源文件。

Or you could open up the watch window while you're debugging and paste in this code to get an array of the resource names in the currently executing assembly.或者您可以在调试时打开监视窗口并粘贴此代码以获取当前执行程序集中的资源名称数组。

System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames()

That being said, the format of your metadata paths should be something like:话虽如此,元数据路径的格式应该类似于:

{my-assembly-name}/{possibly-a-namespace}.{class-name}.{csdl or ssdl or msl} {my-assembly-name}/{possibly-a-namespace}.{class-name}.{csdl or ssdl or msl}

只需键入路径而不是 {Path.To.The.}: res:// /{Path.To.The.}YourEdmxFileName.csdl|res:// /{Path.To.The.}YourEdmxFileName.ssdl| res://*/{Path.To.The.}YourEdmxFileName.msl

In my case none of the answers listed worked and so I'm posting this.在我的情况下,列出的答案都没有奏效,所以我发布了这个。

For my case, building on Visual studio and running it with IIS express worked fine.就我而言,在 Visual Studio 上构建并使用 IIS express 运行它运行良好。 But when I was deploying using Nant scripts as a stand-alone website was giving errors.但是当我使用 Nant 脚本作为独立网站进行部署时,出现了错误。 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.我尝试了上面的所有建议,然后意识到由 nant 脚本生成的 DLL 比 VS 生成的要小得多。 And then I realized that Nant was unable to find the .csdl, .msl and .ssdl files.然后我意识到 Nant 无法找到 .csdl、.msl 和 .ssdl 文件。 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.那么实际上有两种方法可以解决这个问题,一种是在visual studio生成它们后复制所需的文件并将这些文件包含在构建部署中。 And then in Web.config, specify path as:然后在 Web.config 中,将路径指定为:

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

This is assuming you have manually copied the files into bin directory of the website which you are running.这是假设您已手动将文件复制到您正在运行的网站的 bin 目录中。 If it's in a different directory, then modify path accordingly.如果它在不同的目录中,则相应地修改路径。 Second method is to execute EdmGen.exe in Nant script and generate the files and then include them as resources like done in the example below: https://github.com/qwer/budget/blob/master/nant.build第二种方法是在 Nant 脚本中执行 EdmGen.exe 并生成文件,然后将它们作为资源包含在下面的示例中: https ://github.com/qwer/budget/blob/master/nant.build

I had the same problem with a solution which contained projects in a Solution Folder, when they were moved to the Solution Root (in order to overcome a suspected bug with the Mvc3AppConverter due to project locations).我在解决方案文件夹中包含项目的解决方案中遇到了同样的问题,当它们被移动到解决方案根目录时(为了克服由于项目位置而导致的 Mvc3AppConverter 的可疑错误)。

Although the solution compiled after all* project references were re-added as needed, the error was thrown when the website was fired up.虽然根据需要重新添加了所有*项目引用后编译的解决方案,但在启动网站时抛出了错误。

The EDMX is in one of the projects which was moved (the 'Data' project), but of course the lack of a reference to the Data project didn't cause a compile error, just a run-time error. EDMX 位于已移动的项目之一(“数据”项目)中,但当然,缺少对数据项目的引用不会导致编译错误,只是运行时错误。

Simply adding the missing reference to the primary project resolved this problem, no need to edit the connection at all.只需添加对主项目的缺失引用即可解决此问题,根本无需编辑连接。

I hope this helps someone else.我希望这对其他人有帮助。

When I got the metadata issue sorted out, I had a follow-on problem in the form of an invokation exception unable to find a connection string for XXXEntities in app.config (where my goal was no dependency on app.config).当我解决元数据问题时,我遇到了一个后续问题,即调用异常无法在 app.config 中找到 XXXEntities 的连接字符串(我的目标是不依赖于 app.config)。 Through sheer luck I found that referencing System.Data in my unit test project cleared this final hurdle.幸运的是,我发现在我的单元测试项目中引用 System.Data 清除了最后的障碍。 So to summarise:所以总结一下:

  1. Use nuget to install Entity Framework to your unit test project.使用 nuget 将 Entity Framework 安装到您的单元测试项目中。
  2. Ensure System.Data.Entity and System.Data are referenced.确保引用 System.Data.Entity 和 System.Data。
  3. Sort your connection string as described very well here.如此处所述,对您的连接字符串进行排序。
  4. Pass the connection string to your partial class constructor.将连接字符串传递给您的部分类构造函数。

I now have my metadata in a class library which can update from a reference db, and I can point my application and unit tests to any db on any server at runtime.我现在将我的元数据放在一个可以从参考数据库更新的类库中,并且我可以在运行时将我的应用程序和单元测试指向任何服务器上的任何数据库。

Addendum: When I moved my edmx to a folder, I got the error again.附录:当我将我的 edmx 移动到一个文件夹时,我再次收到错误消息。 After a bit of research, I found that you want your metadata string to look like: metadata=res://EPM.DAL/Models.EPM.csdl, where EPM.DAL is the name of the assembly and EPM.edmx is in the models folder.经过一番研究,我发现您希望您的元数据字符串看起来像:metadata=res://EPM.DAL/Models.EPM.csdl,其中 EPM.DAL 是程序集的名称,EPM.edmx 在模型文件夹。

Similar problem for me.对我来说类似的问题。 My class name was different to my file name.我的班级名称与我的文件名不同。 The connectionstring generated had the class name and not the file name in. Solution for me was just to rename my file to match the class name.生成的连接字符串具有类名而不是文件名。对我来说,解决方案只是重命名我的文件以匹配类名。

My theory is that if you have more than one edmx file with same name (Model1 for example), it will give that exception.我的理论是,如果您有多个同名的 edmx 文件(例如 Model1),它将给出该异常。 I've got same problem when I decided to name all my edmx files (sitting in different projects) as Model1 because I thought they should be independent.当我决定将所有 edmx 文件(位于不同项目中)命名为 Model1 时,我遇到了同样的问题,因为我认为它们应该是独立的。

I got this error when my emdx file was deleted by a prebuild command, quite simply.当我的 emdx 文件被 prebuild 命令删除时,我收到了这个错误,很简单。 Took me a while before realizing it was that simple.我花了一段时间才意识到这很简单。

Another cause for this exception is when you include a related table in an ObjectQuery, but type in the wrong navigation property name.此异常的另一个原因是当您在 ObjectQuery 中包含相关表时,但键入了错误的导航属性名称。

Example:例子:

var query = (from x in myDbObjectContext.Table1.Include("FKTableSpelledWrong") select x);

In my case this was because I was building the connection string using a EntityConnectionStringBuilder.就我而言,这是因为我正在使用 EntityConnectionStringBuilder 构建连接字符串。 Make sure your Metadata property is using the Model name (including the namespace)确保您的元数据属性使用模型名称(包括命名空间)

I got this problem after moving a large solution from one folder in Source Control Explorer to another.将大型解决方案从源代码管理资源管理器中的一个文件夹移动到另一个文件夹后,我遇到了这个问题。 We don't check the package folder into Team Foundation and so I think VS downloaded packages automatically.我们不会将包文件夹检入 Team Foundation 中,因此我认为 VS 会自动下载包。 This upgraded my EF form v6.1.2 to v6.1.3.这将我的 EF 表单 v6.1.2 升级到了 v6.1.3。

The problem went away when I downgraded to the original v6.1.2.当我降级到原来的 v6.1.2 时问题就消失了。

I had same issue on 27 Sep 2019.我在 2019 年 9 月 27 日遇到了同样的问题。

My API is in Dot net core Targeting to .net framework.我的 API 在 Dot net core Targeting to .net 框架中。 edmx is in a different class library which is in .net framework only. edmx 位于仅在 .net 框架中的不同类库中。

I observed that when I try to call that edmx from API .. for some reason I got that error.我观察到,当我尝试从 API 调用该 edmx 时 .. 出于某种原因,我收到了该错误。

What I did is, go to the obj folder of API and delete everything.我所做的是,转到 API 的 obj 文件夹并删除所有内容。 then clean the API project and try again and that worked for me.然后清理 API 项目并重试,这对我有用。

Sometimes the assembly that contains the model is not loaded:有时未加载包含模型的程序集:

    [TestMethod]
    public void TestOpenWithConfigurationAfterExplicit()
    {
        String dummy = typeof(MallApp).Assembly.FullName;  
        //force the assembly loaded.
        using (DbContext ctx = new DbContext("name=MyContainer))
        {
        }
    }

The type MallApp lives in the same assembly as the entity model. MallApp类型与实体模型位于同一程序集中。 Without the explicit loading, an System.Data.MetadataException will be thrown.如果没有显式加载,将抛出System.Data.MetadataException

I was reflecting an old program, I faced the same problem.我正在反映一个旧程序,我遇到了同样的问题。 I went through previous answers, and I succeeded to solve it by putting the 3 files of "Model.csdl", "Model.ssdl" and "Model.msl" in the bin directory, and also beside the entities class.我浏览了之前的答案,通过将“Model.csdl”,“Model.ssdl”和“Model.msl”三个文件放在bin目录中以及实体类旁边,我成功解决了这个问题。 After that change the metdata part of the entities connection string in web.config to be:之后,将 web.config 中实体连接字符串的元数据部分更改为:

metadata=~/bin/Model.csdl|~/bin/Model.ssdl|~/bin/Model.msl

and the program ran successfully withput displaying this exception.并且程序成功运行,但显示此异常。

Also in my case syntax error in the XML structure of the EDMX was the reason.在我的例子中,EDMX 的 XML 结构中的语法错误也是原因。 I recognized that after VS was not able to show the graph diagram and opened the XML editor instead.我意识到在 VS 无法显示图表后,我打开了 XML 编辑器。

An earlier merge was the root cause of the syntax error.较早的合并是语法错误的根本原因。

I also received this error upon upgrading my project to .NET 6, and none of the previous solutions solved my issue.我在将我的项目升级到 .NET 6 时也收到此错误,并且以前的解决方案都没有解决我的问题。

You may want to check if your.edmx file has the following two properties set as follows:您可能需要检查您的 .edmx 文件是否设置了以下两个属性,如下所示:

  • Build Action: EntityDeploy构建操作:EntityDeploy
  • Copy to Output Directory: Copy Always复制到Output目录:一直复制

Ultimately my issue was that the files referenced in my.edmx file were not being generated.最终我的问题是没有生成 my.edmx 文件中引用的文件。

我从解决方案中的所有项目中删除了 \bin 和 \obj 文件夹,然后重建了解决方案,它工作正常

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

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