【问题标题】:EF Core - EntityTypeBuilder One to Many Relationship?EF Core - EntityTypeBuilder 一对多关系?
【发布时间】:2019-07-31 22:30:56
【问题描述】:

我有点困惑,关于如何在 EF Core 2.1 中建立关系。我一直在用流利的方式做。

我有

public class Employee : IdentityUser
{
    public int BranchId { get; set; }
    public Branch Branch { get; set; }

}

 public class Branch
    {
        public int Id { get; set; }
        public int CompanyId { get; set; }
        public Company Company { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }

public class EmployeerConfig : IEntityTypeConfiguration<Employee>
{
    public void Configure(EntityTypeBuilder<Employee> builder)
    {
        builder.ToTable("Employees");
    }
}

public class BranchConfig : IEntityTypeConfiguration<Branch>
    {
        public void Configure(EntityTypeBuilder<Branch> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.Id).ValueGeneratedOnAdd();

            builder.HasMany(x => x.Employees);

            builder.ToTable("Branches");
        }
    }

我看到的所有示例大多使用 dbcontext 模型构建器,但不再需要这种方式,因为您现在可以像我一样使用拆分它。

我首先为 Company 和 Branch 建立了 2 种关系,我什至没有指定关系,但我建立了它知道的数据库,但是当我尝试与 Employee 和 Branch 建立关系时,关系没有形成。

这让我在分支配置中添加了builder.HasMany(x =&gt; x.Employees),现在关系有效,但是我不确定我是否在 Employee 区域中指定了要完成的内容?

我也不知道我是否还需要将虚拟添加到我的集合中,以及为什么如果我不使用 ToTable() 并构建我的数据库,所有表名都是缩写的,我认为这是自动的。

【问题讨论】:

  • 您解决了吗?我遇到了完全相同的问题

标签: c# entity-framework-core


【解决方案1】:

EmployeerConfig 很好,如果你愿意,你可以添加密钥

对于分支配置添加这一行希望这会帮助你。

     builder.HasMany(x => x.Employee).WithOne(b => b.Branch).HasForeignKey(b => b.BranchId)
    .OnDelete(DeleteBehavior.Cascade);

【讨论】:

    猜你喜欢
    • 2017-10-26
    • 2021-10-11
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多