简体   繁体   English

EF与外键的多对多关系

[英]Many to Many relationship EF with foreign keys

I want to configure many to many relationship between 2 entities but I would also like to expose their foreign keys. 我想配置2个实体之间的多对多关系,但我也想公开它们的外键。 I found only one concrete solution online like following: 我在网上仅找到一种具体的解决方案,如下所示:

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

But map left and right key does not take a properties from my models so I do not have access to them and they will not be filled when I query. 但是地图的左右键不会从我的模型中获取属性,因此我无权访问它们,并且在查询时不会填充它们。 So, I do not have access to my foreign key properties. 因此,我无权访问我的外键属性。

Hope I was able to explain my problem. 希望我能解释我的问题。 Can anyone suggest any other option? 有人可以建议其他选择吗?

You can create an associative model that has keys from the two entities: 您可以创建一个具有两个实体中的键的关联模型:

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; }
}

Entity 1: 实体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; }
}

Entity 2: 实体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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM