C# – Can’t have the same table names in different entity framework models

centity-frameworknetsql server

My application uses two different SQL 2008 databases. The databases have a few tables with the same name, ie. Users. I would like to use EF4 for both these databases. However, when I run my application and it hits the objectcontext creation of the second database, I get the following error:

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

Does this mean I can't use two databases with (partly) the same table names in the same application? They are in different namespaces, different edmx models, different projects, etc.

P.S. One of the models is designer-generated and uses POCO classes and the other is inferred from the database and is tightly coupled to EF.

Best Answer

To use the "default convention based mapping" the following 2 approaches will work:

1) The collision is caused by the connection string using a wild card:

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

Since * does not work your project you can define multiple connection strings to hard code the assembly containing the edmx.

2) create a helper

    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);
    }

Update 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))