实体框架与来自不同数据库的相同表名冲突

实体框架与来自不同数据库的相同表名冲突

问题描述:

我在Visual Studio 2012(C#)中将Entity Framework 4与MVC 3一起使用。

I am using Entity Framework 4 with MVC 3 in Visual Studio 2012 (C#).

我先使用数据库;有两个单独的数据库,每个数据库都有自己的名称空间和两个单独的edmx文件。每个数据库都有一个具有相同名称和字段(但内容不同)的表。当我添加第二个表时,我开始出现编译错误。

I am using database first; there are two separate databases each with its own namespace and with two separate edmx files. Each database has a table with the same name and fields (but different content). When I added the second table I started to get compile errors.

Ambiguity between 'Interface.CodeFormStatus.FormStatusCodeID' 
and 'Interface.CodeFormStatus.FormStatusCodeID' 

似乎有些复杂的解决方法,或者我可以重命名其中之一桌子。没有一个简单的解决方案,因为这肯定是一个相当普遍的问题。

There seem to be some complex workarounds or I could rename one of the tables. Is there not a straightforward solution as this must be a fairly common issue.

我遇到了两个数据库的情况(一个旧版本),我需要将两者都集成到一个项目中。自然,几乎每个名称都冲突。

I ran into a situation where I had two databases (one an older version of the other) and I needed to integrate both into a single project. Naturally, almost every name conflicted.

我为每个数据库创建了两个单独的edmx文件,并将每个文件放在自己的命名空间中以求清楚。然后,我编辑了每个实体名称,以反映该数据库来自哪个数据库(例如,这两个数据库中的 Activities分别变为 v13Activities和 v14Activities)。

I created two separated edmx files for each database, and put each in its own namespace for clarity. I then edited each entity name to reflect which database it was coming from - (e.g. "Activities", which was in both, became "v13Activities" and "v14Activities").

对于要在两个数据库之间进行镜像的操作,我编写了一个包含两个上下文的包装器。这使我的代码没有那么重复,而且同步问题也更少。

For operations which were to be mirrored between both databases, I wrote a wrapper that included both contexts. This made my code was much less repetitive, and it had less synchronization issues.

希望这种方法对其他人有所帮助-似乎这是一个晦涩的问题,而这个答案是Google的最佳搜索结果之一!

Hope this approach helps someone else - it seems like this is an obscure question, and this answer was one of the top results on Google!

更新:在EF 6.1+中,还有另一种解决方案。您可以具有冲突名称,并在使用代码优先从数据库选项。我会提倡这种解决方案,因为旧的XML .edmx样式将从EF Core开始逐步淘汰

Update: In EF 6.1+, there is another solution. You can have "conflicting" names, and separate them with simple namespacing when using the "Code First From Database" option. I would advocate for this solution going forward, as the old XML .edmx style is going to be phased out starting in EF Core.