开发者

save many to many relationship - EF

I've 3 tables: User, Course, UserCourse

how do I save the different courses for a user on table UserCourse using Entity 开发者_运维问答Framework?

Thanks


Usually, entity framework converts your link table to a direct relationship. That is, you will be able to do this:

someUser.Courses.Add(someCourse);
someUser.Courses.Remove(someOtherCourse);

someCourse.Users.Add(someOtherUser);

At least if your UserCourse table is set up in a way that enables EF to do that. (i.e. only two columns with the two keys of User and Course set as PK)


UserCourse table should be junction table for EF to understand many-to-many relationship. For example: UserId (PK), CourseId(PK)

After that you can simply add entities to entity collections.

var context = new MyModel();
var user1 = new User { Name = "u1" };
var user2 = new User { Name = "u1" };
context.Users.Add(user1);
context.Users.Add(user2);
var math = new Course { Name = "Math" };
context.Courses.Add(math);
math.Users.Add(user1);
math.Users.Add(user2);
context.SaveChanges();

The same logics for adding course to user: user1.Courses.Add(math);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜