与外键有很多关系EF

时间:2014-02-17 05:05:49

标签: c# entity-framework fluent

我想配置2个实体之间的多对多关系,但我还想公开它们的外键。我在网上找到了一个具体的解决方案,如下所示:

modelBuilder.Entity<E1>()
                            .HasMany(t => t.E1s)
                            .WithMany(t => t.E2s)
                            .Map(m =>
                            {
                                m.ToTable("E1E2");
                                m.MapLeftKey("FKE1");
                                m.MapRightKey("FKE2");
                            });

但是左右键地图不会从我的模型中获取属性,因此我无法访问它们,并且在查询时它们不会被填充。所以,我无法访问我的外键属性。

希望我能够解释我的问题。任何人都可以建议任何其他选择吗?

1 个答案:

答案 0 :(得分:1)

您可以创建一个包含来自两个实体的键的关联模型:

public class AssociativeEntity
{
    [Key]
    public Guid AssociativeEntityId { get; set; }
    public Guid Entity1Id { get; set; }
    public Guid Entity2Id { get; set; }

    [Display(Name = "Entity1", ResourceType = typeof(Resources.Language))]
    public virtual Entity1 Entity1 { get; set; }
    [Display(Name = "Entity2", ResourceType = typeof(Resources.Language))]
    public virtual Entity2 Entity2 { get; set; }
}

实体1:

public class Entity1
{
    [Key]
    public Guid Entity1Id { get; set; }

    /* Describe the other properties here */

    [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
    public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
}

实体2:

public class Entity2
{
    [Key]
    public Guid Entity2Id { get; set; }

    /* Describe the other properties here */

    [Display(Name = "AssociativeEntities", ResourceType = typeof(Resources.Language))]
    public virtual ICollection<AssociativeEntity> AssociativeEntities { get; set; }
}