【问题标题】:Fluent API - how to map custom relation table?Fluent API - 如何映射自定义关系表?
【发布时间】:2016-10-31 18:24:19
【问题描述】:

我的课程可能如下所示:

public class Group
{
    public int Id {get; set;}
    public ICollection<Group> IsMemberOf {get; set;}
}

组可以是其他组的成员。 Id db 我有表 Group 和表 GroupGroup。在 ModelBuilder 中,我使用此代码来定义映射。

modelBuilder.Entity<GroupGroup>()
            .ToTable("GroupGroup")
            .HasKey(e => new { e.GroupId, e.MemberGroupId });
modelBuilder.Entity<Group>()
            .ToTable("Group")
            .Ignore(e => e.IsMemberOf);

好吧,我的问题是如何使用 Fluent API 将组从关系表 GroupGroup 映射到属性 IsMemberOf?我对 ef、Fluent API 等非常陌生,我知道我应该让 ef 创建自己的关系表,但由于连接到 AD 和其他系统,我必须使用这种方式。有什么办法可以做到这一点?

非常感谢任何提示。

【问题讨论】:

    标签: c# sql entity-framework fluent


    【解决方案1】:

    看起来您需要一个多对多关联,因为这个 GroupGroup 关联表。一种映射方式是:

    modelBuilder.Entity<Group>()
        .HasMany(g => g.IsMemberOf)
        .WithMany()
        .Map(m => m.MapLeftKey("ChildGroupId")
                   .MapRightKey("GroupId")
                   .ToTable("GroupGroup")
            );
    

    这意味着您的类模型中没有GroupGroup 实体类。如果您执行如下 LINQ 语句,EF 会通过设置所有必要的连接来填充 IsMemberOf 集合:

    var groups = context.Groups.Include(g => g.IsMemberOf).ToList();
    

    我不知道为什么你的映射中有这行 .Ignore(e =&gt; e.IsMemberOf),但应该删除它。

    您甚至可以双向进行映射:

    public class Group
    {
        public int Id {get; set;}
        public ICollection<Group> IsMemberOf { get; set; }
        public ICollection<Group> HasMembers { get; set; }
    }
    

    还有映射:

    modelBuilder.Entity<Group>()
        .HasMany(g => g.IsMemberOf)
        .WithMany(g => g.HasMembers)
        .Map(m => m.MapLeftKey("ChildGroupId")
                   .MapRightKey("GroupId")
                   .ToTable("GroupGroup")
            );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-06
      相关资源
      最近更新 更多