Does anyone know if there's a trick to getting EF, code first, to map two tables with the same name, but different schemas?
This is the error I'm getting:
The type 'DAL.dbo.Employer' was not mapped. Check that the type has not been
explicitly excluded by using the Ignore method or NotMappedAttribute data
annotation. Verify that the type was defined as a class, is not primitive,
nested or generic, and does not inherit from EntityObject.
I'm working, during downtime, to put a new POC DAL together for our existing database using EF, instead of the legacy crap we have now. Everything was going fine until I added a table that had the same name as another table, but in a different schema.
Here is the original table, with reference to other table:
namespace DAL.dbo
{
public partial class Employer
{
public Employer()
{
Employers = new List<Brokers.Employer>();
}
//table definition
public virtual ICollection<Brokers.Employer> Employers { get; set;}
}
}
Here is the new table, which has a FK to the dbo table.:
namespace DAL.Brokers
{
public partial class Employer
{
public Guid EmployerID { get; set;}
//table definition
public virtual dbo.Employer dboEmployer{ get; set;}
}
}
And for those that may want it, here are the relevant parts of my OnModelCreating method:
modelBuilder.Entity<Brokers.Employer>().HasKey(k => k.ID);
modelBuilder.Entity<Brokers.Employer>().ToTable("Employers", "Brokers");
modelBuilder.Entity<dbo.Employer>().HasKey(k => k.ID);
modelBuilder.Entity<dbo.Employer>().ToTable("Employers", "dbo");
modelBuilder.Entity<dbo.Employer>().HasMany(m => m.Employers).WithRequired(r => r.dboEmployer).HasForeignKey(f => f.EmployerID).WillCascadeOnDelete(false);
I'll skip all the minutia, so here's the relevant parts of the DbContext class:
public class DALContext: DbContext
{
public DALContext(string connection) : base(connection) {}
public DbSet<Brokers.Employer> brokerEmployers { get; set;}
public DbSet<dbo.Employer> dboEmployers { get; set;}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//see excerpt from above
}
}
You need to use unique class names even if the model classes are in different namespaces. There's an explanation here:
EF Code first, how to register same table name with different schema?