Towseef Ahmed
Towseef Ahmed

Reputation: 19

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.

Upvotes: 0

Views: 449

Answers (1)

Serge
Serge

Reputation: 43870

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

Upvotes: 2

Related Questions