简体   繁体   English

MVC3 实体框架多对多与附加列

[英]MVC3 Entity Framework many-to-many with additional column

I'm new to asp.net, mvc3 and entity framework.我是 asp.net、mvc3 和实体框架的新手。 I'm trying to develop a mvc3 programm with entity framework and code-first.我正在尝试使用实体框架和代码优先开发一个 mvc3 程序。 So I have two classes with a many-to-many relationship.所以我有两个具有多对多关系的类。

One class called "User" the other one is "Course".一个 class 称为“用户”,另一个是“课程”。

 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.例如,我还没有管理它来自动将创建课程的用户添加到CourseUsers表中。

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.它是 model 中的一个新实体,具有两个一对多关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM