0

我創建了兩個表。
表1:ParentId和ParentName字段的父表。在此ParentId中是主鍵。
表2:具有ChildId和ChildName字段的子表。在此ChildId中是主鍵。
我想要ParentId和ChildId到另一個表中。所以用ParentId1,ChildId1.I在名稱MappingParentChild中創建表需要此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(); 
} 
} 

我該怎麼做,請幫幫我。

+0

您使用的是實體框架。如果是這樣,哪個版本?我認爲這是你題目中的EF。 –

+0

爲什麼你要創建'MappingParentChild'類的具體原因是什麼?因爲EF不需要它來創建多對多的關係 – SOfanatic

回答

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); 
} 
} 
相關問題