多对多关系中的代码优先外键配置

时间:2013-08-16 09:36:40

标签: asp.net-mvc asp.net-mvc-3 entity-framework asp.net-mvc-4

我创建了两个表 表1:具有ParentId和ParentName字段的父表。在此ParentId是主键 表2:具有ChildId和ChildName字段的子表。在此ChildId是主键 我想将ParentId和ChildId放到另一个表中。使用ParentId1,ChildId1.I的名称MappingParentChild中的icreated表将此ParentId1和ChildId1作为外键。 我怎么能做到这一点。

public class Parent
{
public int ParentId { get; set; } //Primary key
public string ParentName { get; set; }
}
public class Child
{
public int ChildId { get; set; } //Primary key
public string ChildName { get; set; }
}
public class MappingParentChild
{
public int Id { get; set; }
public int ParentId1 { get; set; } // want Foreign key for Parent(ParentId)
public int ChildId1 { get; set; }// want Foreign key for Child(ChildId)
}
public class MappingParentChildConfiguration :EntityTypeConfiguration<MappingParentChild>
{
public MappingParentChildConfiguration()
{
ToTable("MappingParentChild");
Property(m => m.Id).IsRequired();
Property(m => m.ParentId1).IsRequired();
Property(m => m.ChildId1).IsRequired();
}
}

我怎么能这样做。请帮助我。

1 个答案:

答案 0 :(得分:1)

public class Parent
{
public int ParentId { get; set; }
public string ParentName { get; set; }
public virtual ICollection<MappingParentChild> parent{ get; set; }
}

public class Child
{
public int ChildId { get; set; }
public string ChildName { get; set; }
public virtual ICollection<MappingParentChild> child { get; set; }
}

public class MappingParentChild
{
public int Id { get; set; }
public int ParentId1 { get; set; }
public int ChildId1 { get; set; }
public virtual Parent pt{ get; set; }
public virtual Child Ch{ get; set; }
}

public class MappingParentChildConfiguration : EntityTypeConfiguration<MappingParentChild>
{
public MappingParentChildConfiguration()
{
ToTable("MappingParentChild");
Property(m => m.Id).IsRequired();
HasRequired(m => m.pt).WithMany(e => e.parent).HasForeignKey(m => m.ParentId );
HasRequired(m => m.ch).WithMany(e => e.child ).HasForeignKey(m => m.ChildId );
}
}