简体   繁体   中英

EF Core - EntityTypeBuilder One to Many Relationship?

I am a bit confused, about how to do relationships in EF Core 2.1. I been doing it the fluent way.

I have

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

All the examples I seen mostly to use dbcontext model builder, but that way is no longer needed as you can now use split it up as I done.

I done my relationships 2 ways first for Company and Branch I don't even specify the relationship yet went I build my db it knows, however when I try to do that with Employee and Branch the relationship was not formed.

This made me add builder.HasMany(x => x.Employees) in the branch config and now the relationship works, however I am not sure if I have specify something in the Employee area to make to complete?

I also don't know if I need to still add virtual to my collections anymore and why if I don't use ToTable() and build my db, all the table names are abbreviated, I thought that was automatic.

EmployeerConfig is fine you can add key if yoy want

For Branch Config add this line hope this'll help you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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