2010-11-01 140 views
16

我的應用程序使用兩個不同的SQL 2008數據庫。數據庫有幾個同名的表,即。 Users。我想爲這兩個數據庫使用EF4。然而,當我跑我的應用程序,它擊中的ObjectContext創建第二個數據庫,我收到以下錯誤:在不同的實體框架模型中不能有相同的表名稱?

Multiple types with the name 'User' exist in the EdmItemCollection in different namespaces. Convention based mapping requires unique names without regard to namespace in the EdmItemCollectionto namespace in the EdmItemCollection

這是否意味着我不能使用兩個數據庫與(部分)相同的表名同一個應用程序?他們在不同的命名空間,不同的edmx模型,不同的項目等。

P.S.其中一個模型是設計師生成的,使用POCO類,另一個模型是從數據庫中推斷出來的,並與EF緊密耦合。

+0

在設計器中更改其中一個實體名稱是否會解決此問題?不過,這似乎有點不方便。 – 2010-11-01 13:24:06

+0

我希望有一個不同的解決方案。這是一個數據庫轉換應用程序(從舊數據庫到新數據庫),因此有相同的表名。除了結束了錯誤的類型名稱之外,在設計器中重命名它們意味着在新的應用程序中會進行一些嚴重的重構。 – Carvellis 2010-11-01 13:30:05

+0

我有不同的實體名稱相同的問題... – juanora 2016-11-25 09:59:45

回答

10

錯誤的含義是,他說:你不能在你的場景中使用基於默認約定的映射。改爲使用自定義數據庫映射。 Scott Guthrie有關於this的詳細博客文章。

22

要使用「默認的慣例基於映射」下面的方法2將工作:

1) 碰撞通過使用通配符連接字符串引起:

metadata=res://*/Repositories.EntityFramework.Model.csdl|res://*/Repositories.EntityFramework.Model.ssdl|res://*/Repositories.EntityFramework.Model.msl; 

由於*確實不工作你的項目,你可以定義多個連接字符串來硬編碼包含edmx的程序集。

2)創建一個幫助

public static EntityConnection GetEfConnectionString(this string sqlConnectionString) 
    { 
     var cs = string.Format(@"metadata=res://{0}/Repositories.EntityFramework.Model.csdl|res://{0}/Repositories.EntityFramework.Model.ssdl|res://{0}/Repositories.EntityFramework.Model.msl;provider=System.Data.SqlClient;provider connection string=""" + sqlConnectionString + @"""", 
      Assembly.GetCallingAssembly().FullName 
     ); 

     return new EntityConnection(cs); 
    } 

更新2017年:

public static string GetEfConnectionString(this string sqlConnectionString, Type type) 
    { 
     string cs = 
      string.Format(
       @"metadata=res://{0}/Models.Model.csdl|res://{0}/Models.Model.ssdl|res://{0}/Models.Model.msl;provider=System.Data.SqlClient;provider connection string=""" + 
       sqlConnectionString + @"""", 
       type.Assembly.FullName 
       ); 
     return cs; 
    } 


    // usage: don't "new" EntityConnection. See 2012 comment. 
    string connString = ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString.GetEfConnectionString(); 
    using(var entities = new XyzEntities(connString)) 
+0

這幫了我很多。我修改了我的T4模板以實現類似的東西,以便所有模型都可以使用配置中的一個連接字符串,但仍然只能讀取其元數據。謝謝。 – 2011-05-19 12:36:21

+0

我剛剛得到upvoted,並想更新此...不要新的EntityConnection否則你需要管理打開/關閉對象。您的幫助者應該將連接字符串作爲字符串返回,並在objectcontext ef4.0或dbcontext ef4.1上使用重載構造函數。 – 2012-01-06 03:45:34

+1

+ 1爲更簡單的解決方案,無需代碼優先。 – christoph 2013-10-30 13:54:36

1

我有同樣的問題,但我的解決辦法是從項目中刪除的MODEL \ EDMX的DLL,因爲它從一個不同的項目中複製,然後重建它。 解決了一切!

相關問題