EF 5 Code First Mapping问题

时间:2015-06-01 15:32:36

标签: c# entity-framework poco

有没有人知道是否有一个技巧来获得EF,代码优先,映射两个具有相同名称但不同模式的表?

这是我得到的错误:

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.

我在停机期间工作,使用EF为我们现有的数据库放置一个新的POC DAL,而不是我们现在拥有的遗留垃圾。一切都很顺利,直到我添加了一个与另一个表具有相同名称的表,但是在不同的模式中。

这是原始表,参考其他表:

namespace DAL.dbo
{
   public partial class Employer
   {
     public Employer()
     {
       Employers = new List<Brokers.Employer>();
     }
     //table definition
     public virtual ICollection<Brokers.Employer> Employers { get; set;}
   }
}

这是新表,它与dbo表有一个FK。:

namespace DAL.Brokers
{
  public partial class Employer
  {
    public Guid EmployerID { get; set;}
    //table definition
    public virtual dbo.Employer dboEmployer{ get; set;}
  }
}

对于那些可能需要它的人,以下是我的OnModelCreating方法的相关部分:

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

我将跳过所有细节,所以这里是DbContext类的相关部分:

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

1 个答案:

答案 0 :(得分:2)

即使模型类位于不同的命名空间中,您也需要使用唯一的类名。这里有一个解释:

EF Code first, how to register same table name with different schema?