EF 5代码优先映射问题

本文关键字:映射 问题 代码 EF | 更新日期: 2023-09-27 17:51:20

有没有人知道,如果有一个技巧,让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
  }
}

EF 5代码优先映射问题

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

EF代码第一,如何注册相同的表名与不同的模式?