Search code examples
entity-framework-6edmxef-database-first

Entity Framework - Cannot create multiple DbContexts that reference the same table. - Workaround


As per the title, the scenario is: one c-sharp project, with two folders, each containing two EDMX contexts...

Myproj\NSOne\ModelOne.edmx, Myproj\NSTwo\ModelTwo.edmx;

Generally this works well, until you share the same table across both contexts. No problem at design time, Entity Classes get generated under different namespaces, it's only at runtime that you get the following error:

Schema specified is not valid. Errors: The mapping of CLR type to EDM type is ambiguous because multiple CLR types match the EDM type 'TB_MyTable'. Previously found CLR type 'Namespace.NSOne.TB_MyTable', newly found CLR type 'Namespace.NSTwo.CIXModel.TB_MyTable'.

While searching for answers, I've come across a Github issue that pretty much say "it is too hard / not trivial" we won't fix. https://github.com/aspnet/EntityFramework6/issues/362

However, a workaround is to edit the EDMX file, as mentioned in that github issue.

<ConceptualModels>
    <Schema Namespace="ConsoleApplication33" 
        Alias="Self" 
        annotation:UseStrongSpatialTypes="false"
        xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" 
        xmlns:customannotation="http://schemas.microsoft.com/ado/2013/11/edm/customannotation" 
        xmlns="http://schemas.microsoft.com/ado/2009/11/edm">
    <EntityType Name="Person" 
        customannotation:ClrType="MyApp.Person, MyApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
        <Key>
        <PropertyRef Name="Id" />
        </Key>
        <Property Name="Id" Type="Int32" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
        <Property Name="Name" Type="String" MaxLength="Max" FixedLength="false" Unicode="true" />
    </EntityType>
    <EntityContainer Name="Town" customannotation:UseClrTypes="true">
        <EntitySet Name="People" EntityType="Self.Person" />
    </EntityContainer>
    </Schema>
</ConceptualModels>

My problem / question is, in my project the above xml fragment with "ConceptualModels" is nowhere to be found ?!

Where do I even begin to look ? Within my edmx files (thru visual studio), I can only see, for example,

  • ModelOne.edmx
    • ModelOne.Context.tt
    • ModelOne.Designer.csharp
    • ModelOne.edmx.diagram
    • ModelOne.tt

EntityFramework.dll, EntityFramework.SqlServer.dll versions are:

File version: 6.2.61023.0 Product version: 6.2.0-61023


Solution

  • Not really an answer, but it appears Microsoft has abandoned EF Database-first (EDMX), so the next option for me two months after asking the question was to get rid of it myself from my current project.

    In future projects I'll also use EF Code-first, given that VS still allows the strongly-typed classes to be generated easily.