C# EntityContainer 名称必须是唯一的。已定义名为“实体”的 EntityContainer

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2060278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:08:55  来源:igfitidea点击:

The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined

c#.netvisual-studioentity-frameworkexception-handling

提问by Keith Barrows

For a little background:

了解一下背景:

I have a DLL project with the following structure:

我有一个具有以下结构的 DLL 项目:

Rivworks.Model (project)  
  \Negotiation (folder)  
      Model.edmx (model from DB #1)  
  \NegotiationAutos (folder)  
      Model.edmx (model from DB #2)  

I have moved the connection strings from this project's app.config to the web.config file. They are notin the ConnectionString section. Rather, I have a static class that consumes part of the web.config and exposes them to my app as AppSettings.[settingName].

我已将连接字符串从该项目的 app.config 移至 web.config 文件。它们不在ConnectionString 部分中。相反,我有一个静态类,它使用 web.config 的一部分并将它们作为 AppSettings.[settingName] 公开给我的应用程序。

<FeedAutosEntities_connString>metadata=res://*/;provider=System.Data.SqlClient;provider connection string='Data Source=db4;Initial Catalog=RivFeeds;Persist Security Info=True;User ID=****;Password=&quot;****&quot;;MultipleActiveResultSets=True'</FeedAutosEntities_connString>
<RivWorkEntities_connString>metadata=res://*/NegotiationAutos.NegotiationAutos.csdl|res://*/NegotiationAutos.NegotiationAutos.ssdl|res://*/NegotiationAutos.NegotiationAutos.msl;provider=System.Data.SqlClient;provider connection string='Data Source=db2;Initial Catalog=RivFramework_Dev;Persist Security Info=True;User ID=****;Password=&quot;****&quot;;MultipleActiveResultSets=True'</RivWorkEntities_connString>

I have 2 classes, one for each Context and they look like this:

我有 2 个类,每个 Context 一个类,它们看起来像这样:

namespace RivWorks.Model
{
    public class RivWorksStore
    {
        private RivWorks.Model.Negotiation.Entities _dbNegotiation;

        public RivWorksStore(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbNegotiation = new RivWorks.Model.Negotiation.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.Negotiation.Entities NegotiationEntities()
        {
            return _dbNegotiation;
        }
    }
}

namespace RivWorks.Model
{
    public class FeedStoreReadOnly
    {
        private RivWorks.Model.NegotiationAutos.Entities _dbFeed;

        public FeedStoreReadOnly(string connectionString, string metadata, string provider)
        {
            EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
            entityBuilder.ConnectionString = connectionString;
            entityBuilder.Metadata = "res://*/";    // metadata;
            //entityBuilder.Provider = provider;
            _dbFeed = new RivWorks.Model.NegotiationAutos.Entities(entityBuilder.ConnectionString);
        }

        public RivWorks.Model.NegotiationAutos.Entities ReadOnlyEntities()
        {
            return _dbFeed;
        }
    }
}

You will note that the MetaData is being rewritten to a short version.

您会注意到 MetaData 正在被重写为简短版本。

When I comment out that line in each class I get this error:

当我在每个类中注释掉该行时,我收到此错误:

Unable to load the specified metadata resource.

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

When I leave that line in in each class I get this error:

当我在每个班级中保留该行时,我收到此错误:

Schema specified is not valid. Errors:

Negotiation.Model.csdl(3,4) : error 0019: The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined.

指定的架构无效。错误:

Negotiation.Model.csdl(3,4):错误 0019:EntityContainer 名称必须是唯一的。已定义名为“实体”的 EntityContainer。

I know it is something simple, something obvious. Any suggestions welcome...

我知道这很简单,很明显。欢迎任何建议...

采纳答案by Craig Stuntz

Your two EDMX files probably have the same entity container name. You need to change (at least) one of them.

您的两个 EDMX 文件可能具有相同的实体容器名称。您需要更改(至少)其中之一。

In the GUI designer, open Model Browser. Look for a node that says "EntityContainer: Entities". Click it. In Properties, change Nameto something else. Save and rebuild.

在 GUI 设计器中,打开模型浏览器。查找显示“EntityContainer: Entities”的节点。点击它。在属性中,更改Name为其他内容。保存并重建。

回答by jpo

HiHymaning this, since it is the top Google result for the error message.

劫持这个,因为它是错误消息的顶级谷歌结果。

In case anyone else encounters this while only using a single model/context: I once ran into this problem because the assembly containing the model/context was renamed and a copy with the previous name remained in the bin directory of the application. The solution was to delete the old assembly file.

万一其他人在仅使用单个模型/上下文时遇到此问题:我曾经遇到过这个问题,因为包含模型/上下文的程序集已重命名,并且具有以前名称的副本保留在应用程序的 bin 目录中。解决方案是删除旧的程序集文件。

回答by TombMedia

I have found a way to save multiple containers with the same name (namespaced of course).

我找到了一种方法来保存多个具有相同名称的容器(当然是命名空间的)。

In EF5 and VS2012 you can set three different namespaces. First you can click on the edmx file in the solution browser and in the properties windows you can set the "Custom Tool Namespace", you can click on the *.Context.tt file right below the edmx and set another namespace there, and finally thanks to a lead from Mr Stuntz awesome answer I realized that by opening the edmx file and clicking in the white space you get another namespace field under Schema in the properties window.

在 EF5 和 VS2012 中,您可以设置三个不同的命名空间。首先,您可以在解决方案浏览器中单击 edmx 文件,然后在属性窗口中设置“自定义工具命名空间”,您可以单击 edmx 正下方的 *.Context.tt 文件并在那里设置另一个命名空间,最后感谢 Stuntz 先生的精彩回答,我意识到通过打开 edmx 文件并单击空白区域,您会在属性窗口中的 Schema 下获得另一个命名空间字段。

Think we're done, not quite, I know you can see the Entity Container Name field and will try to change the name there but that doesn't seem to work, you get a little error that pops up. Ensure that all your edmx files have an individual namespace there. (I ensured I had a unique namespace in all three places)

认为我们已经完成了,还没有完全完成,我知道您可以看到实体容器名称字段,并会尝试在那里更改名称,但这似乎不起作用,您会收到一个弹出的小错误。确保所有 edmx 文件在那里都有一个单独的命名空间。(我确保我在所有三个地方都有一个唯一的命名空间)

Then go to your Model Browser and right click on EntityContainer: Entity to go to properties and change the name of your container(s). From that window with the namespace set everywhere I was able to get multiple contexts with the same name. I was dealing with things like blahcontext and blahcontextcontainer all of a sudden even though they were in different folders.

然后转到您的模型浏览器并右键单击 EntityContainer: Entity 以转到属性并更改容器的名称。从那个在任何地方都设置了命名空间的窗口中,我能够获得多个具有相同名称的上下文。我突然处理了诸如 blahcontext 和 blahcontextcontainer 之类的东西,即使它们在不同的文件夹中。

When you see that its a namespace problem. Or lack thereof.

当你看到它是一个命名空间问题时。或缺乏。

回答by MrFlo

I had the problem too but my solution was to clean the bin directory and then remove the connection string with the entity container name. Then I could rename my entities and put back the connection string.

我也有这个问题,但我的解决方案是清理 bin 目录,然后删除带有实体容器名称的连接字符串。然后我可以重命名我的实体并放回连接字符串。

回答by Rob Sedgwick

I renamed my project but the old file was still in the bin folder. I just had to delete the old DLL from the bin folder.

我重命名了我的项目,但旧文件仍在 bin 文件夹中。我只需要从 bin 文件夹中删除旧的 DLL。

回答by d512

I just ran into this. It looks like somehow Entity Framework got into a bad state in terms of what tables it thought it needed to add.

我刚遇到这个。就它认为需要添加的表而言,实体框架似乎以某种方式进入了一种糟糕的状态。

Normally EF will not recognize that a new table has to be created until you put the line

通常 EF 不会识别必须创建新表,直到您放置该行

public virtual DbSet<NewTable> NewTable { get; set; }

inside your context class.

在您的上下文类中。

However, EF somehow got into a bad state where the mere presence of the NewTable class in my solution was triggering it to think that it needed to generate that table. So by the time the above line in the context triggered it to create a NewTable table, it already thought it had done it, hence the error about duplicate entities.

然而,EF 不知何故进入了一种糟糕的状态,在我的解决方案中仅仅存在 NewTable 类就会触发它认为它需要生成该表。因此,当上下文中的上述行触发它创建一个 NewTable 表时,它已经认为它已经完成了,因此出现了关于重复实体的错误。

I just removed the NewTable class from my solution, commented things out so it would compile again (thankfully there wasn't too much of this), then added a new migration to make sure it was blank as it should have been. Then once things were back into a more predictable state, I re-added the NewTable class back into the solution and adding the migration worked fine.

我刚刚从我的解决方案中删除了 NewTable 类,将内容注释掉,以便它可以再次编译(幸好没有太多这样的内容),然后添加了一个新的迁移以确保它应该是空白的。然后,一旦事情恢复到更可预测的状态,我将 NewTable 类重新添加回解决方案并添加迁移工作正常。

回答by Sagar Shirke

I had a same problem in my asp.net website, to resolve the problem I purposely added compile time error in one of the cs file in the app code by removing a semicolon, then I rectified the compilation problem by adding semicolon again.

我在我的 asp.net 网站上遇到了同样的问题,为了解决这个问题,我故意通过删除分号在应用程序代码中的一个 cs 文件中添加了编译时错误,然后我通过再次添加分号来纠正编译问题。

This process caused application to compile again.After this error got vanished.

此过程导致应用程序再次编译。此错误消失后。

回答by kepler

The other cause of this problem, your add model in any solution project and change your model project.

此问题的另一个原因,您在任何解决方案项目中添加模型并更改您的模型项目。

--PROJECT A --> MODEL.EDMX

--- WEB CONFIG -->Entity Connection

--PROJECT B

--- WEB CONFIG -->Entity Connection

Later, I think this structure is bad and Change project.

后来觉得这个结构不好改项目。

--PROJECT A
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING 

--PROJECT B
using PROJECT.C;
WEB.CONFIG - USE PROJECT C APP.CONFIG CONNECTIONSTRING 

--PROJECT C  (CLASS LIBRARY) --> MODEL.EDMX 
--- APP.CONFIG -->Entity Connection

Everything was fine but I get an error. Error Detail : The EntityContainer name must be unique. An EntityContainer with the name 'Entities' is already defined

一切都很好,但我收到一个错误。 错误详细信息:EntityContainer 名称必须是唯一的。已定义名为“实体”的 EntityContainer

Because I forgot change Web.Config files.

因为我忘了更改 Web.Config 文件。

OLD WEB.CONFIG

旧的 WEB.CONFIG

    <add name="donatelloEntities" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=donatello;persist security info=True;user id=1;password=1;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

NEW WEB.CONFIG

新的网络配置

 <add name="donatelloEntities" connectionString="metadata=res://*/EntityModel.Model.csdl|res://*/EntityModel.Model.ssdl|res://*/EntityModel.Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=donatello;user id=sa;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />

This Problem is Simple but may cause loss of time. I wanted to give an example. I hope is useful.

这个问题很简单,但可能会导致时间损失。我想举个例子。我希望有用。

Thanks.

谢谢。

回答by Dan Bechard

In my case, the problem was caused by my connection string in Web.config being named the same thing as my entities container class.

在我的例子中,问题是由于我在 Web.config 中的连接字符串被命名为与我的实体容器类相同的东西。

Change

改变

<add name="ConflictingNameEntities" connectionString="metadata=res://*/blahblah

to

<add name="ConflictingNameEntitiesConnection" connectionString="metadata=res://*/blahblah

and regenerate the container class by right-clicking ConflictingNameModel.Context.tt in Solution Explorer and clicking "Run Custom Tool".

并通过在解决方案资源管理器中右键单击 ConflictingNameModel.Context.tt 并单击“运行自定义工具”来重新生成容器类。

回答by lloyd

To solve the issue Entity 6.2.0, VS 2017, single edmx

解决Entity 6.2.0、VS 2017、单一edmx的问题

I changed the name of my model.edmx to another name, built the project, then changed it back to the original name.

我将我的 model.edmx 的名称更改为另一个名称,构建项目,然后将其改回原来的名称。