【问题标题】:Mapping from many-to-many in database to one-to-many in domain从数据库中的多对多映射到域中的一对多
【发布时间】:2015-03-14 15:02:40
【问题描述】:

我在实体框架中有一个映射挑战。

在数据库中,我在两个表之间有一个多对多关系,其中一个中间表的 PK 如下所示:

我需要将此关系映射到一对多域实体关系,如下所示:

如何使用 Fluent API 进行映射?

【问题讨论】:

  • 是否需要仅使用一个导航属性进行一对多或多对多映射?
  • 您不能将其映射为一对多,因为这需要直接外键。
  • 我需要映射到一对多,我不能添加一个属性只是为了有一个外键......

标签: .net many-to-many entity-framework-6 one-to-many ef-fluent-api


【解决方案1】:

您可以使用导航属性并在模型中设置 Dependents 表:

public class Title
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Person> Dependents { get; set; }
}

public class Person
{
    public int Id { get; set; }

    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<Title> Titles { get; set; }
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Title>()
            .HasMany<Person>(t => t.Dependents)
            .WithMany()
            .Map(d =>
            {
                d.MapLeftKey("Title_Id");
                d.MapRightKey("Person_Id");
                d.ToTable("Dependents");
            });
    }
}

【讨论】:

  • 谢谢麦克斯!按预期工作。
猜你喜欢
  • 2019-02-27
  • 2019-07-03
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
  • 2014-04-07
相关资源
最近更新 更多