Thanushka
Thanushka

Reputation: 1445

Entity Framework model first error on mapping table

I'm new to entity framework and when I'm creating some sample projects I got following error .

" Entity type 'StudentSubject' is not mapped."

Following is the table diagram.

enter image description here

The issue is it is not generating the mapping for StudentSubject which holds the records of many to many mapping of student and subject tables.

But if I introduce a new column as Id to table StudentSubject and make it the primary key and remove the composite primary key then it works. I want to know why is this happening and is the way I did is the rite way to do it in model first approach.

Upvotes: 0

Views: 306

Answers (2)

NinjaNye
NinjaNye

Reputation: 7126

I can't see your code but this is how I usually map it. Note this requires no fluent api mapping

public class Student
{
    public int Id { get; set; }
    public string FirstName {get; set; }
    public string LastName {get; set; }

    public virtual ICollection<StudentSubject> StudentSubjects { get; set; }
}

public class Subject
{
    public int Id { get; set; }
    public string Name {get; set; }

    public virtual ICollection<StudentSubject> StudentSubjects { get; set; }
}

public class StudentSubject
{
    [Key]
    [Column(Order = 1)]
    public int StudentId { get; set; }

    [Key]
    [Column(Order = 2)]
    public int SubjectId{ get; set; }

    public virtual Student Student { get; set; }
    public virtual Subject Subject { get; set; }
}

Upvotes: 1

Yucel
Yucel

Reputation: 2673

I suggest to use the fluent api for mapping because of naming convention sometimes is not suit the requests.

Following code should be work as you desired;

protected override void OnModelCreating
   (DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
            .HasMany(t => t.Subject)
            .WithMany(t => t.Student)
            .Map(m =>
            {
                m.ToTable("StudentSubjects");
                m.MapLeftKey("StudentId");
                m.MapRightKey("InstructorID");
            });
}

Upvotes: 1

Related Questions