【问题标题】:Entity Framework referencing columns in foreign key differs from number of referenced columns外键中的实体框架引用列与引用列的数量不同
【发布时间】:2015-01-06 21:57:15
【问题描述】:

我首先使用的是实体框架代码,我正在尝试让我的迁移/数据库正常工作(使用 -update-database 命令),但我不断收到此错误:

System.Data.SqlClient.SqlException (0x80131904):外键中的引用列数与表“dbo.FileSections”中引用的列数不同。

这直接发生在这个 SQL 命令之后(EF 正在变魔术):

ALTER TABLE [dbo].[FileSections] ADD CONSTRAINT [FK_dbo.FileSections_dbo.Sections_Section_Id] FOREIGN KEY ([Section_Id]) REFERENCES [dbo].[Sections] ([Id], [EventName]) ON DELETE CASCADE

我的问题的简化版本是一个事件(字符串“名称”的主键)可以有很多部分,一个部分(整数“Id”的主键)可以有很多文件(主键为字符串“ID”)。简化的类是:

public class Event {
    public string Name { get; set; }
    public List<Section> Sections { get; set; }
}

public class Section {
    public int Id { get; set; }
    public string EventName { get; set; }
    public string Title { get; set; }
    public List<File> Files { get; set; }
}

public class File {
    public string Id { get; set; }
    public int SectionId { get; set; }
    public string FileName { get; set; }
}

我也是先用代码,这个设置是:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    modelBuilder.Entity<Event>()
        .HasKey(X => X.Name);
    modelBuilder.Entity<Event>()
        .HasMany(X => X.Sections)
        .WithRequired(X => X.Event)
        .WillCascadeOnDelete();    

    modelBuilder.Entity<Section>()
        .HasKey(x => x.Id); 
    modelBuilder.Entity<Section>()
        .HasRequired(x => x.Event)
        .WithMany(x => x.Sections)
        .HasForeignKey(x => x.EventName);
    modelBuilder.Entity<Section>()
        .HasMany(x => x.Files)
        .WithRequired(x => x.Section)
        .HasForeignKey(x => x.SectionId)
        .WillCascadeOnDelete();

    modelBuilder.Entity<File>()
        .HasKey(x => x.Id);
    modelBuilder.Entity<File>()
        .HasRequired(x => x.Section)
        .WithMany(x => x.Files)
        .HasForeignKey(x => x.SectionId);
}

我做错了什么?我也尝试过使用复合主键(因此也使用复合外键),但这仍然给了我同样的错误。我真的束手无策,拥有一个包含实体的实体当然不会这么难。

【问题讨论】:

  • 什么是数据库架构?

标签: c# entity-framework ef-code-first entity-framework-migrations fluent


【解决方案1】:

事实证明,Visual Studio 2013 是问题所在 - 它试图应用初始迁移,而不是实际的最新迁移(尽管已经应用了初始迁移)。我使用this answer 修复了 VS 的迁移问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多