3

I'm new to asp.net, mvc3 and entity framework. I'm trying to develop a mvc3 programm with entity framework and code-first. So I have two classes with a many-to-many relationship.

One class called "User" the other one is "Course".

 public class Course : IValidatableObject
 {
         [...]
         public virtual ICollection<User> Users { get; set; }
         [...]
 }

 public class User : IValidatableObject
 {
         [...]
         public virtual ICollection<Course> Courses { get; set; }
         [...]
 }

So, this works. But now I need an additional field which safes the status of the registration for a course. Is there an easy way I don't know?

I tried it this way:

 public class Course : IValidatableObject
 {
         [...]
         public virtual ICollection<CourseUser> CourseUsers { get; set; }
         [...]
 }

 public class User : IValidatableObject
 {
         [...]
         public virtual ICollection<CourseUser> CourseUsers { get; set; }
         [...]
 }

 public class CourseUser
 {
     [Key, ForeignKey("Course"), Column(Order = 0)]
     public int Course_ID { get; set; }
     [Key, ForeignKey("User"), Column(Order = 1)]
     public string User_ID { get; set; }

     public int Status { get; set; } //{ pending, approved }

     public virtual Course Course { get; set; }
     public virtual User User { get; set; }
 }

But this makes it much more difficult to add or edit related data. For example I didn't managed it yet to automatically add the user who created the course to the CourseUsers table.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gesh
  • 33
  • 3

1 Answers1

1

No there is no easier way to do that. Once you add any additional field to your junction table it must be mapped as entity to allow you access to that field. It is not pure many-to-many relation any more. It is a new entity in your model with two one-to-many relations.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Ok, thx for the answer. Maybe you can help me with updating the related tables. I get the user_id through `Membership.GetUser().ProviderUserKey.ToString()` but I don't really know how to update my related table during the creation of a new course. I read a lot of tutorials on www.asp.net, but they are a bit confusing, I think. – Gesh Jul 07 '11 at 11:41
  • 2
    This is not how it works here. You ask a question and you got an answer. If you have a new question ask it as separate one. Comments are not for asking another unrelated questions. – Ladislav Mrnka Jul 07 '11 at 11:46