Configure One-to-Many relationship using Fluent API in Entity Framework Core

Configure One-to-Many relationship using Fluent API in Entity Framework Core

Entity Framework Core makes it very easy for us to configure relationships using Fluent API. In this tutorial I will explain how to configure One-to-Many relationship using Fluent API.

Note: Conventions in EF are sufficient to create One-to-Many relationships and basically you don’t need Fluent API to create this One-to-Many relationship. Only for code maintenance and understanding you can use Fluent API for creating One-to-Many relationships.

Consider the following Country and City entities.

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

    public string Name { get; set; }

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

    public string Name { get; set; }

    public int FKCountry { get; set; }

    public Country Country { get; set; }
}

I will Configure the one-to-many relationship for these 2 entities using Fluent API by overriding the OnModelCreating method in the context class, as shown below.

public class CompanyContext : DbContext
{
    public DbSet<City> City { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseSqlServer(@"Server=vaio;Database=Company;Trusted_Connection=True;");
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //Write Fluent API configurations here

        modelBuilder.Entity<City>()
                    .HasOne(e => e.Country)
                    .WithMany(e => e.City)
                    .HasForeignKey(e => e.FKCountry);
    }
}

On performing migration you will get Country and City tables created having foreign key FKCountry on the city table.

one to many relationship

Understanding how One-to-Many Relationship is configured

  • 1. Start by configuring one entity (either Country or City class). I start with City class (modelBuilder.Entity).
  • 2. Next .HasOne(e => e.Country) specifies that the entity contains the reference property of other type (i.e. Country) for one-to-one relationship.
  • 3. Next I move to the other end of the relationship with .WithMany(e => e.City). It specifies that the ‘Country’ entity includes collection navigation property of City type.
  • 4. The .HasForeignKey(e => e.FKCountry) specifies that the property FKCountry is the foreign key for the City table.

You can also configure the relationship starting with Country entity instead of the City entity. See the below code:

modelBuilder.Entity<Country>()
            .HasMany(e => e.City)
            .WithOne(e=>e.Country)
            .HasForeignKey(e => e.FKCountry);

Cascade Delete in Fluent API for Foreign Keys

EF Core behaves differently when the parent entity of the foreign key is deleted. You can configure this using Fluent API.

You can instruct EF Core to – delete the child row if the related parent row is deleted, or set foreign key to null, or prevent delete.

This is done from .OnDelete() method.

On the below code I have set ‘DeleteBehaviour’ as Cascade which means the dependent entity will be deleted when its parent entity is deleted.

modelBuilder.Entity<City>()
            .HasOne(e => e.Country)
            .WithMany(e => e.City)
            .HasForeignKey(e => e.FKCountry)
            .OnDelete(DeleteBehavior.Cascade); //Cascade behaviour

The DeleteBehaviour has 4 values:

  • Cascade : Dependent entities will be deleted if its principal entity is deleted.
  • ClientSetNull: The values of foreign key properties in the dependent entities will be set to null when its parent entity is deleted.
  • Restrict: Prevents Cascade delete.
  • SetNull: The values of foreign key properties in the dependent entities will be set to null when its parent entity is deleted.

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.