Entity Framework Core - How to correctly map relationships with composite key?

c# entity-framework-core json

Question

I have the following table structure

Facility

Id int (PK)
Name 

Visit

FacilityId int 
Hour int
Value

Table Visit has the composite key (FacilityId, Hour)

The entity classes are defined as

class Facility
{
    public int Id { get; set; }
    public string Name { get; set; }   
    public ICollection<Visit> Visits { }
}

class Visit
{
    public int FacilityId { get; set; }
    public int Hour { get; set; }
    public int Value { get; set; }
    public Facility Facility { get; set; }
}

My DbContext class has the following in OnModelCreating method:

modelBuilder.Entity<Facility>()
                .ToTable("Facility")
                .HasKey(f => f.Id);
modelBuilder.Entity<Facility>()
                .HasMany(f => f.Visits)

modelBuilder.Entity<Visit>()
                .ToTable("Visits")
                .HasKey(v => new { v.FacilityId, v.Hour});
modelBuilder.Entity<Visit>()
                .HasOne(a => a.Facility)
                .WithMany(a => a.Visits)
                .HasForeignKey(a => a.FacilityId)
                .HasPrincipalKey(a => a.Id); 

Here is the resulting JSON from my ASP.Net Core WebAPI

[{"id":1,"name":"Facility1","visits":null},      {"id":2,"name":"Facility2","visits":null}]

Question: why is the visits JSON null? What configuration am I missing?

Thanks in advance.

1
1
12/29/2016 6:28:12 PM

Accepted Answer

The EF have by default turned on Lazy Loading it's a reason why you get "visits":null. But it's normal. Need to use Eager loading by using the .Include() function on your query. See docs for specific examples usage eager loading.

This sample code getall Facility and Visits

 var allData =  context.Facility
               .Include(d => d.Visits)
               .ToList();
3
12/29/2016 5:44:17 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