I am creating a basic ASP.NET Core Web API which contains a list of countries/locations/places of interest.
I have created all the methods for location which are a child of the country object and everything is working as expected.
However I am trying to create a method for adding a point of interest (child of the location object) but it just doesn’t save anything to the database, even though the code is laid out identically to how I am doing it for the location.
Here is my controller:
var finalPlaceOfInterest = mapper.Map<PlaceOfInterest>(placeOfInterestForCreation);
await repository.AddPlaceOfInterestAsync(locationId, finalPlaceOfInterest);
await repository.SaveChangesAsync();
Repository code
public async Task AddPlaceOfInterestAsync(int locationId, PlaceOfInterest placeOfInterest)
{
var location = await GetLocationAsync(locationId);
if (location != null)
{
location.PlacesOfInterest.Add(placeOfInterest);
}
}
public async Task<bool> SaveChangesAsync()
{
return (await context.SaveChangesAsync() >= 0);
}
My PlaceOfInterest
entity class is defined like this:
public class PlaceOfInterest
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
[ForeignKey("LocationId")]
public Location? Location { get; set; }
public int LocationId { get; set; }
}
After calling repository.SaveChangesAsync
, the finalPlaceOfInterest
object should get populated with its ID and the Location
& LocationID
properties, but they are not being set and nothing is being persisted to the database.
I have identical code for creating a Location
, but with the Country
as its parent, and it works correctly and is saved. After calling the SaveChangesAsync
method, the ID
, Country
& CountryID
properties are populated.
What am I missing? Starting to go a bit mad here as I can’t figure out why this won’t work. I’ve added migrations and updated my database & all the tables & columns are correct.
George Murray is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Guys I solved it and of course it was me being stupid! On my Location entity I had the places of interest property declared like this:
public ICollection<PlaceOfInterest> PlacesOfInterest = new List<PlaceOfInterest>();
I forgot to include the {get; set;}
for it. Thanks for the replies.
George Murray is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.