【发布时间】:2019-04-26 13:44:15
【问题描述】:
我正在使用本网站建议的以下两个类:https://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx
public class Barca
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BarcaID { get; set; }
public virtual ICollection<Imbarco> Imbarco { get; set; }
public virtual Imbarco ImbarcoBase { get; set; }
}
public class Imbarco
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ImbarcoID { get; set; }
public virtual ICollection<Barca> Barche { get; set; }
public virtual ICollection<Barca> BaseBarche { get; set; }
}
我需要创建 1 对 M 关系,为此我使用了以下 2 个导航属性:
public virtual Imbarco ImbarcoBase { get; set; }
public virtual ICollection<Barca> BaseBarche { get; set; }
但我还需要 M 对 M 关系,为此我使用了:
public virtual ICollection<Imbarco> Imbarco { get; set; }
public virtual ICollection<Barca> Barche { get; set; }
当我尝试在 M 到 M 中添加新项目时,未在数据库中创建桥接表,如上面报告的链接中所述,并且我尝试在 VisualStudio 中生成的 edmx 文件创建了一个 0.. 1 到 M 和 M 到 0..1 的关系,而不是 m 到 M。 我做错了什么?
【问题讨论】:
-
您可能需要另一个类来表示桥(连接)表,该表具有其他表的两个外键作为属性。
-
我在 2014 年的论坛中找到了您的建议,但我认为桥接表是在 EF6 中自动创建的,如此处所述entityframeworktutorial.net/code-first/…,或者我错了吗?
-
你是否在每个类的构造函数中添加了集合初始化?
-
你的意思是像:public Barca() { this.Imbarco = new HashSet
();不,我没有添加它们...我现在试试 -
@WMmaster 我认为这取决于您是否将
code-first方法与EF一起使用。
标签: c# entity-framework-6 asp.net-4.5