实体框架中的ForeignKey错误

时间:2016-05-08 17:33:00

标签: c# asp.net-mvc-5 entity-framework-5

我正在计划一个简单的两个表结构:

1)教师表:

public class TeacherAccount
{
    [DataType(DataType.Text), Required()]
    public string Name { get; set; }

    [DataType(DataType.Text), Required()]
    public string Address { get; set; }

    [DataType(DataType.EmailAddress), Required(), Key]
    public string Email { get; set; }

    [DataType(DataType.Password), Required()]
    public string Password { get; set; }

    [DataType(DataType.Password), Compare("Password"), Required(), NotMapped]
    public string ConfirmPassword { get; set; }

    public bool Activated { get; set; }

}

2)老师教授的科目:

public class Teacher_Subject_Map
{
    [ForeignKey("TeacherAccount")]
    public string Email { get; set; }
    public string Subjects;
}

我的理念是: 对于识别教师的电子邮件,可以有多个科目,由该老师讲授。

我怎么会得到这个:

  

属性上的ForeignKeyAttribute'电子邮件'在类型上   ' xpertsdesk.Models.Teacher_Subject_Map'无效。导航   property' TeacherAccount'在依赖类型上找不到   ' xpertsdesk.Models.Teacher_Subject_Map&#39 ;. Name值应为a   有效的导航属性名称。

作为mvc5中的错误。

我想做什么:

Create table Teacher(Email varchar(30) Primary Key, Other Details);
Create table Subjects(Email varchar(30) References Teacher(Email), Subject varchar(30));

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果一个科目只能由一位老师教授(一对多关系):
在这种情况下,将不会有映射表。

public class Subject
{
    [Key]
    public string Name { get; set; }

    // This will hold the Key of Teacher
    public string TeacherEmail { get; set; }

    [ForeignKey("TeacherEmail")]
    public virtual Teacher Teacher { get; set; }
}

public class Teacher
{
    /* the original properties comes here, e.g. Email */
    public string Email { get; set; }

    // Navigation property for taught subjects
    public virtual ICollection<Subject> Subjects { get; set; }
}

如果一个科目可以由更多的老师教授(多对多关系):
Subject类就是这样的。

public class Subject
{
    [Key]
    public string Name { get; set; }

    /* other properties if needed */

    public virtual ICollection<Teacher> Teachers { get; set; }
}

然后您可以在自己的DbContext类中配置多对多关系:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<Teacher>()
        .HasMany(teacher => teacher.Subjects)
        .WithMany(subject => subject.Teachers)
        .Map(c =>
        {
            c.ToTable("Teacher_Subject_Map");
            c.MapLeftKey("TeacherEmail");
            c.MapRightKey("SubjectName");
        });
}