[英]Entity Framework Code First Many to Many Relationship with Existing Entities
I have the following situation: 我有以下情况:
modelBuilder.Entity<RecurringAppointment>()
.HasMany(ra => ra.StaffMembers)
.WithMany();
So a staff member (inherited from user) can have many recurring apointments and vice versa. 因此,工作人员(从用户继承)可以有很多重复的约会,反之亦然。 Now, when I try to add staff members to recurringAppointment.StaffMembers like this ... 现在,当我尝试将职员添加到recurringAppointment.StaffMembers这样的时候...
[Invoke]
public void ApplyStaffMembersToRecurringAppointment(int recurringAppointmentId, int[] staffMemberIds)
{
var staffs = DbContext.Users
.OfType<Staff>()
.Where(s => staffMemberIds.Contains(s.Id))
.ToList();
var recurringAppointment = DbContext.RecurringAppointments
.Include("StaffMembers")
.Single(ra => ra.Id == recurringAppointmentId);
foreach (var staff in staffs)
{
recurringAppointment.StaffMembers.Add(staff);
DbContext.Users.Attach(staff);
}
DbContext.RecurringAppointments.Attach(recurringAppointment);
DbContext.Entry(recurringAppointment).State = EntityState.Modified;
DbContext.SaveChanges();
}
... it just won't save the changes. ...它只是不会保存更改。 When I add values manually to the database it works perfectly, so the relation should be set up correctly. 当我手动将值添加到数据库时,它可以完美工作,因此应正确设置该关系。
I looked at tons of similar entries, but they all either didn't save or didn't attach. 我查看了大量的类似条目,但是它们要么都没有保存,要么没有附加。 The code gets executed (I can debug). 代码被执行(我可以调试)。 What could be the problem? 可能是什么问题呢?
Does your Staff Object have a navigation collection referring back to your Recurring appointment? 您的Staff对象是否有一个导航集合,该导航集合回溯到您的定期约会? When I had nav collections on both ReccuringAppointments and StaffMembers, the above code did not save changes. 当我在ReccuringAppointments和StaffMembers上都拥有导航集合时,上面的代码没有保存更改。
If you only have the navigation collection on ReccuringAppointmets however it did work - unless I had set AutoDetectChangesEnabled = false
in my configuration. 如果您仅在ReccuringAppointmets上具有导航集合,则它确实可以工作-除非我在配置中设置了AutoDetectChangesEnabled = false
。
If neither of these cases happened, the code worked perfectly - if these cases aren't true for you, can you post your context/entities for more information? 如果这两种情况均未发生,则代码可以正常工作-如果这些情况对您而言不正确,您可以发布上下文/实体以获取更多信息吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.