I have two model classes ServiceProvider.cs & Club.cs
one service provider can have many clubs in it. However ServiceProvider.cs
has a virtual collection of clubs in it. As shown below
public class ServiceProvider
{
public int ServiceProviderId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public virtual ICollection<Club> Clubs { get; set; }
}
public class Club
{
public int ClubId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public virtual ServiceProvider serviceProvider { get; set; }
public int ServiceProviderId { get; set; }
}
I have implemented a repository pattern to query the MS Sql server, if i return my repository's _serviceProvider
GetAll()
method it works fine, and i get all the serviceprovider objects in PostMan
.
public IEnumerable<ServiceProvider> Get()
{
return _serviceProvider.GetAll();
}
But if i return the GetAllWithClubs()
method of repository then i get run time exception here. Problem is: I am unable to get all service providers along with their clubs collection. However, i have already debugged my code before putting question here, I am getting all the service providers along with their clubs collection perfectly fine. I am sure data fetching from database is fine, problem coming in sending response back from Get() Action method.
public IEnumerable<ServiceProvider> Get()
{
return _serviceProvider.GetAllWithClubs();
}
Error i am getting in Postman is
output in visual studio is
I have tried searched solution of .toList()
in front of GetAllWithClubs()
plus returning ActionResult
which came with Asp.net core 2.1 (Not supported in my case 2.0). I believe this is not a duplicate question.
Implementation of GetAll()
and GetAllWithClubs()
methods are below.
public IEnumerable<ServiceProvider> GetAllWithClubs()
{
return _context.ServiceProviders
.Include(c => c.Clubs);
}
In Repository.cs
public IEnumerable<T> GetAll()
{
return _context.Set<T>();
}