许多一对多使用EF code首先关系 [英] Many-to-many relationships using EF Code First
问题描述
我有两个类定义是这样的:
I have two classes defined as such:
public class Questionnaire
{
public int QuestionnaireID { get; set; }
public string Title { get; set; }
public bool Active { get; set; }
public virtual ICollection<Question> Questions { get; set; }
public virtual ICollection<Vendor> Vendors { get; set; }
}
public class Vendor
{
public int VendorID { get; set; }
public string VendorName { get; set; }
public virtual ICollection<Questionnaire> OpenQuestionnaires { get; set; }
public virtual ICollection<Questionnaire> SubmittedQuestionnaires { get; set; }
public virtual ICollection<QuestionnaireUser> QuestionnaireUsers { get; set; }
}
我beleive这是建立这些类之间的许多一对多的关系,正确的方法,并且在该项目建成后,我会希望创建三个表。
I beleive this is the correct way to establish a many-to-many relationship between these classes, and when the project is built, I would expect three tables to be created.
然而,当我试图以涉及一份问卷,以两个不同的供应商,我收到试图保存更改时出现以下错误(context.SaveChanges()):
However, when I attempt to to relate one Questionnaire to two different Vendors, I receive the following error when attempting to save the changes (context.SaveChanges()):
*违反了多重限制。关系QuestionnaireApp.Models.Vendor_OpenQuestionnaires'的作用Vendor_OpenQuestionnaires_Source具有多重1或0..1。*
*Multiplicity constraint violated. The role 'Vendor_OpenQuestionnaires_Source' of the relationship 'QuestionnaireApp.Models.Vendor_OpenQuestionnaires' has multiplicity 1 or 0..1.*
如果我给你一份调查问卷,只有一个卖方,保存更改,然后将其分配到另一个,并再次保存更改我不再得到的错误;然而该问卷随后只与最后卖方它被指定,这表明(充其量)有正在创建一对多的关系。
If I assign a Questionnaire to only one Vendor, save the changes and then assign it to another and again save changes I no longer get the error; however the Questionaire is then related only to the last Vendor to which it was assigned, indicating that (at best) there is a one-to-many relationship being created.
我希望有什么毛病我声明了这些类之间的许多一对多的关系的方式,或者是有一些我需要添加上下文类鼓励的relationsip,但不支持这样也许很多一对多的关系,否则不能使用code首先被创造的?
I'm hoping that there is something wrong with the way I'm declaring the many-to-many relationship between these classes, or perhaps there is something I need to add to the context class to "encourage" the relationsip, but perhaps many-to-many relationships like this are not supported, or cannot be created using "Code First"?
感谢您的时间,
杰森
推荐答案
去图,经过一个小时左右的搜索,我去找到确切答案,30秒后我张贴我的问题。
Go figure, after an hour or so of searching, I go and find the exact answer 30 seconds after I post my question.
解决的办法是添加以下上下文类:
The solution was to add the following to the context class:
modelBuilder.Entity<Vendor>()
.HasMany<Questionnaire>(x => x.OpenQuestionnaires)
.WithMany(x => x.Vendors)
.Map(x =>
{
x.MapLeftKey("vID");
x.MapRightKey("qID");
x.ToTable("VendorQuestionnaires");
});
我找到了答案通过阅读这个堆栈溢出职位:的 EF code首先许多到许多不工作
这篇关于许多一对多使用EF code首先关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!