开发者

MVC3 Entity Framework many-to-many with additional column

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 t开发者_Python百科he course to the CourseUsers table.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜