如何修复“在模型生成期间检测到一个或多个验证错误:”,以便实体未定义密钥

时间:2017-06-22 18:23:12

标签: entity-framework asp.net-mvc-5 code-first foreign-key-relationship ef-migrations

所以这已经花费了我删除数据库的费用,而我仍在努力解决这个问题。 :@

我正在使用EF6,Identity Framework并使用CodeFirst来建模我的数据库。它一直工作正常,直到我必须在Identity表(ApplicationUser:IdentityUser)和自定义表(Report)之间创建关系。它是多个外键关系,其中Reports有两个FK引用,即published_by& handled_by列,指向AppUser表中的相应用户。它创造得很好。

但是在迁移之后,当我开始运行应用程序时,我不断收到此验证错误,该应用程序表示我的所有自定义表(如Reports)都没有定义键。虽然我已经使用FluentAPI在各自的Mapping类中定义了它们。

public class ReportMap : EntityTypeConfiguration<Report>
{
    public ReportMap()
    {
      HasKey(one => one.site_report_id)
    }
}
// similarly in every Mapping class their key is defined already othewise my build wouldn't
   have worked before as well.

我可以在SQL-Management-Studio和ServerExplorer中清楚地看到Primarykeys。他们在那里,为什么我仍然得到这个验证错误。

对于那些想知道我是如何创建这种关联的人。以下是代码。

public class ApplicationUser : IdentityUser
{
  ...
  // Navigation Propertiess
  public virtual ICollection<Report> Published_Reports { get; set; }
  public virtual ICollection<Report> Handled_Reports { get; set; }
  ...}


public class Report
{
  ...
    // Navigation Properties
    public string published_by_id { get; set; }
    public string handled_by_id { get; set; }
    public virtual ApplicationUser Published_By{ get; set; }
    public virtual ApplicationUser Handled_By { get; set; }
  ...}

public class ReportMap : EntityTypeConfiguration<Report>
{
    public ReportMap()
    {
        HasKey(one => one.site_report_id);
        HasRequired(o => o.Published_By)
                   .WithMany(m => m.Published_Reports)
                   .HasForeignKey(o => o.published_by_id)
                   .WillCascadeOnDelete(false);
        HasRequired(o => o.Handled_By)
                   .WithMany(m => m.Handled_Reports)
                   .HasForeignKey(o => o.handled_by_id)
                   .WillCascadeOnDelete(false);
    }
}

以下是我正在使用的上下文

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("MyDB", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

public class Context : ApplicationDbContext
{
    public Context() : base()
    {
    }

    public DbSet<Report> Report { get; set; }
    public DbSet<Other_TBL1> OtherTBL1 { get; set; }
    public DbSet<Other_TBL2> OtherTBL2{ get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new ReportMap());
        modelBuilder.Configurations.Add(new OtherTBL1Map());
        modelBuilder.Configurations.Add(new OtherTBL2Map());

    }
}

0 个答案:

没有答案