Search code examples
c#entity-frameworkef-code-firstdatabase-schemadatabase-migration

Same table name different schema


I have the following tables in my database, all with the same table name but different schema's.

  • dbo.Versions
  • bpm.Versions
  • wf.Version
  • ...

All x.Versions have a FK to the Version table.

I've created the POCO classes from it (this gave me classes like Version, Version1, .... - - I've renamed the classNames to Version and BPMVersion, .... but the mapping still exists to the right table.

This is an example of my mapping of BPMVersion that maps to bpm.Versions

// Primary Key
this.HasKey(t => t.Id);

// Properties
// Table & Column Mappings
this.ToTable("Version", "bpm");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.VersionId).HasColumnName("VersionId");
this.Property(t => t.BPMId).HasColumnName("BPMId");

// Relationships
this.HasRequired(t => t.BPM)
    .WithMany(t => t.BPMVersions)
    .HasForeignKey(d => d.BPMId);
this.HasRequired(t => t.Version)
   .WithMany(t => t.BPMVersions)
    .HasForeignKey(d => d.VersionId);

When creating the Migration script, I've got the following exception: The entity types 'BPMVersion' and 'Version' cannot share table 'Versions' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

I found the following blogs on the internet, it seams that EF has a problem with tables with the same name but different schema (https://entityframework.codeplex.com/workitem/1641 and http://geekswithblogs.net/tonyt/archive/2013/07/02/153327.aspx )

Is there anyway to avoid this problem without renaming the table names?


Solution

  • This has to do with the way EF maps table names. It looks like this is a bug in EF. As of EF 6.1, it is still in Proposed status sadly with Low priority.

    See for details: http://entityframework.codeplex.com/workitem/1641

    Update: EF WorkItem 1641 noted above has been fixed on version 6.1.2