Priyabrata
Priyabrata

Reputation: 1232

ForeignKey error in Entity Framework

I am planning a simple two table structure:

1) Teacher Table :

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) Subjects taught by a teacher :

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

My Concept is : For email identifying a teacher, there can be multiple subjects, which is taught by that teacher.

How ever I am getting this :

The ForeignKeyAttribute on property 'Email' on type 'xpertsdesk.Models.Teacher_Subject_Map' is not valid. The navigation property 'TeacherAccount' was not found on the dependent type 'xpertsdesk.Models.Teacher_Subject_Map'. The Name value should be a valid navigation property name.

as error in mvc5.

What I am trying to do :

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

What am I doing wrong ?

Upvotes: 1

Views: 1392

Answers (1)

Gabor
Gabor

Reputation: 3256

If a subject can be taught by only one teacher (one-to-many relationship):
In this case there will not be a mapping table.

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; }
}

If a subject can be taught by more teachers (many-to-many relationship):
The Subject class would be like this.

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

    /* other properties if needed */

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

And then you can configure the many-to-many relationship in your own DbContext class:

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");
        });
}

Upvotes: 2

Related Questions