简体   繁体   English

使用多对多关系添加对象实体框架

[英]adding object entity framework using many to many relationship

I have a database like lets say a class Student and a class Course. 我有一个数据库,比如说一个班级学生和一个班级课程。 These two have many to many relationship through a join table, holding ids of these two tables which is hidden in EF the way it supposed to. 这两个表通过联接表具有多对多关系,其中包含这两个表的ID(按其应有的方式在EF中隐藏)。

First if I add two courses to a student. 首先,如果我向学生添加两门课程。 Like John.classes.Add(math); John.classes.Add(physics) John.classes.Add(math); John.classes.Add(physics) John.classes.Add(math); John.classes.Add(physics) where 'John', math and physics are objects of their respective classes. John.classes.Add(math); John.classes.Add(physics)其中“ John”,数学和物理是它们各自类的对象。 When i save changes, everything happens the ways it should happen. 当我保存更改时,一切都会以应有的方式发生。 An entry in students table, two entries in courses table and two entries in StudentCourses join table. 学生表中的一个条目,课程表中的两个条目,以及StudentCourses连接表中的两个条目。 All good. 都好。

But then, when i add another student say 'Bob' with same two classes. 但是,当我添加另一个学生时,在两个班上都说“鲍勃”。 Bob.classes.Add(math); Bob.classes.Add(physics); It should add a row in students table adding Bob and two rows in StudentCourses join table. 它应该在学生表中添加一行,从而添加鲍勃,并在StudentCourses连接表中添加两行。 This doesn't happen. 这不会发生。 A row is added to students table but no rows are being added to StudentCourses table giving error of duplicate entry in courses table. 在students表中添加了一行,但没有在studentCourses表中添加任何行,从而导致课程表中重复条目的错误。 Entity Framework is not adding courses because math and physics already exist in courses table but it should add two entries in StudentCourses join table. 实体框架没有添加课程,因为课程表中已经存在数学和物理,但是实体框架应在StudentCourses联接表中添加两个条目。

A work around this is by adding an id column in join table and use this table as normal table and manually add entries in StudentCourses table. 解决方法是在连接表中添加一个id列,然后将此表用作普通表,然后在StudentCourses表中手动添加条目。 But i dont want to do this, I want to know the actual solution. 但是我不想这样做,我想知道实际的解决方案。 这是表架构。根据EF规则隐藏了连接表。 Thanks 谢谢

i solved it by 我解决了

team ct = context.teams.Find(club.id);

if (ct == null)
{ comp.teams.Add(club); }
else
{ ct.competitions.Add(comp); }

context.SaveChanges();

where comp is competition object. 其中comp是竞争对象。 I am sure this is not the actual solution but just a way around. 我确信这不是实际的解决方案,而只是解决方法。 This can't be... 不能这样

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

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