EF Core - EntityTypeBuilder One to Many Relationship?

c# entity-framework-core

Question

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.

1
1
5/24/2018 10:17:37 AM

Popular Answer

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);
0
7/31/2019 2:30:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow