asp.net-mvc – 实体框架无效的列名Id(来自同一主表的两个外键)

我收到此错误:列名’Resource_Id’无效.

我尝试了在论坛上找到的解决方案,但它没有解决我的错误.

这是我的课程:

public class Task 
{
    public int Id { get; set; }

    public string Name { get; set; }
    public int ApproverResourceId { get; set; }
    public int WorkingResourceId { get; set; }

    public virtual Resource ApproverResource { get; set; }
    public virtual Resource WorkingResource { get; set; }
}

资源类

public class Resource
{
    public int Id { get; set; }

    public DateTime CreationDate { get; set; }
    public DateTime UpdateDate { get; set; }

    public virtual ICollection<Task> Tasks { get; set; }
}

ExternalResource

public class ExternalResource : Resource
{
    //public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我在CodeFirst类中添加了这个映射

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Task>()
        .HasRequired(t => t.WorkingResource)
        .WithMany()
        .HasForeignKey(t => t.WorkingResourceId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<Task>()
        .HasRequired(t => t.ApproverResource)
        .WithMany()
        .HasForeignKey(t => t.ApproverResourceId)
        .WillCascadeOnDelete(false);
}

最佳答案 您需要2个导航属性,因为您有2个外键:

public class Resource
{
    public int Id { get; set; }

    public DateTime CreationDate { get; set; }
    public DateTime UpdateDate { get; set; }

    public virtual ICollection<Task> ApproverTasks { get; set; }
    public virtual ICollection<Task> WorkingTasks { get; set; }
}

在DbContext中,您可以在WithMany中指定它们:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Task>()
        .HasRequired(t => t.WorkingResource)
        .WithMany(r => r.WorkingTasks)
        .HasForeignKey(t => t.WorkingResourceId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<Task>()
        .HasRequired(t => t.ApproverResource)
        .WithMany(r => r.ApproverTasks)
        .HasForeignKey(t => t.ApproverResourceId)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<ExternalResource>()
        .ToTable("ExternalResources");
}

由于Table-Per-Type继承,您需要显式告知ExternalResources的表名.

点赞