'I am trying to do eager loading using Entity Framework where I have one-to-many relationship between region and client

This is my Region model class:

public class Region
{
    [Key]
    public Guid Id { get; set; }
    public string Name { get; set; }

    //navigation property
    public virtual ICollection<Client> Clients {get; set;}
}

and my client model class:

public class Client
{
    [Key]
    public Guid Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
    public string Mobile { get; set; }

    public virtual Region Regions {get; set;}
    public string AlternateNumber { get; set; }
    public string Address { get; set; }
    public string ImageName { get; set; }
   
    [NotMapped]
    public IFormFile ImageFile { get; set; }

    [NotMapped]
    public string ImageSrc { get; set; }
}

I am using Fluent API for relation mapping:

 builder.Entity<Client>()
        .HasOne(c => c.Regions)
        .WithMany(x => x.Clients)
        .HasForeignKey(c => c.Id); 

Here I need the RegionId as a foreign key, but I am unable to get it; all I am getting is ClientId as foreign key.



Solution 1:[1]

You have to add a RegionId column to the Client table

public class Client
{
    [Key]
    public Guid Id { get; set; }
   
    .....
   public Guid RegionId {get; set;}
   public virtual Region Region {get; set;}
   ....

and dbcontext

modelBuilder.Entity<Client>(entity =>
            {
                entity.HasOne(d => d.Region)
                   .WithMany(p => p.Clients)
                   .HasForeignKey(d => d.RegionId)
                   .OnDelete(DeleteBehavior.ClientSetNull);
                  
            });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge