C#C
C#3y ago
Connor

✅ Can you add related data to a DbContext like this

I have these classes where Company.Locations navigates to a Locations table and Location.LocationReviews navigates to a LocationReviews table
public class Company : IEntity
{
        public string Id { get; set; }
        public string Name { get; set; }
        public List<Location> Locations {get;set;}
}
public class Location : IEntity
{
        public string Id { get; set; }
        public Company Company { get; set; }
        public List<LocationReview>  LocationReviews { get; set; } = new();
}
public class LocationReview : IEntity
{
        public string Id { get; set; }
        public Location Location { get; set; }
}

I have a generic controller that Im now finding out only works for Company entities.
    [HttpPut]
    public async Task<ActionResult> Save([FromBody] TItem entity)
    {
        var result = await _dbContext.Set<TItem>().Where(x => x.Id == entity.Id)
            .AsNoTracking()
            .FirstOrDefaultAsync();
        if (result != null)
        {
            _dbContext.Update(entity);
        }
        else
        {
            await _dbContext.Set<TItem>().AddAsync(entity);
        }
        await _dbContext.SaveChangesAsync();
        return Ok();
    }
Was this page helpful?