【问题标题】:Many to Many relationship EF with foreign keys多对多关系 EF 与外键
【发布时间】:2014-02-17 05:05:48
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: c# entity-framework fluent


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

    【讨论】:

    • 感谢您的回答。 “关联模型”是指我将为 EF 创建自己的中间表或连接表指定模型吗?
    • 是的。模型构建器的问题是您必须使用关联模型的选项集有限。因此,我建议您手动创建模型。
    • 我无法正确配置连接表。你能帮我解决这个问题吗?我是否要从两个连接实体中删除 List&lt;&gt; 属性?
    • @Md.lbrahim Asnwer 按要求改进。
    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 2011-04-25
    • 2022-10-25
    相关资源
    最近更新 更多