实体框架代码优先 - 列ID无效

时间:2016-03-21 15:21:59

标签: c# asp.net ef-code-first entity-framework-6

我首先拥有一个很棒的ASP.NET MVC应用程序数据库和Entity Framework。它首先适用于db。我想先将应用程序更改为Code。结果我有错误:

{"Invalid column name 'ID'"}

我也有一些继承类。

所有外键映射到OnModelCreating方法,并作为[ForeignKey(“class name”)]属性

映射到类中

这是我的代码的一部分:

[Table("Member")]
public partial class Member
{
    public Member() {}

    public int ID { get; set; }

    [ForeignKey("Seed1")]
    public int? SeedID { get; set; }

    public virtual Seed Seed1 { get; set; }

    ...
}

[Table("Seed")]
public partial class Seed : Member
{
    public Seed()
    {
        Members = new HashSet<Member>();
    }

    public int Locale { get; set; }

    public virtual ICollection<Member> Members { get; set; }

    ...
}

1 个答案:

答案 0 :(得分:0)

解决方案是:

[Table("Member")]
public partial class Member
{
    public Member() {}

    public virtual int ID { get; set; }

    public int? SeedID { get; set; }

    public virtual Seed Seed1 { get; set; }

    ...
}


[Table("Seed")]
public partial class Seed : Member
{
    public Seed()
    {
        Members = new HashSet<Member>();
    }

    public override int ID
    {
        get { return MemberID; }
        set { MemberID = value; }
    }

    [NotMapped]
    public int MemberID { get; set; }

    public int Locale { get; set; }
}

public class SeedMap : EntityTypeConfiguration<Seed>
{
    public SeedMap()
    {
        HasKey(c => c.ID);
        Property(c => c.ID)
            .HasColumnName("MemberID")
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        HasMany(e => e.Members)
            .WithOptional(e => e.Seed1)
            .HasForeignKey(e => e.SeedID);
    }
}