【问题标题】:Code First Foreign Key Configuration in Many to Many Relationships多对多关系中的 Code First 外键配置
【发布时间】:2013-08-18 16:19:09
【问题描述】:

我创建了两个表。
表 1:具有 ParentId 和 ParentName 字段的父表。在此 ParentId 是主键。
表 2:具有 ChildId 和 ChildName 字段的子表。在此 ChildId 是主键。
我想将 ParentId 和 ChildId 放入另一个表中。所以我创建了名为 MappingParentChild 和 ParentId1、ChildId1 的表。我希望这个 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();
}
}

我该怎么做。请帮帮我。

【问题讨论】:

  • 您是否使用实体框架。如果有,是哪个版本?我假设它是您标题中的 EF。
  • 您创建MappingParentChild 类的任何具体原因?因为 EF 不需要它来创建多对多关系

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


【解决方案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 );
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多