I got some error but I couldnt fix it. I want to add a new city with a country name but country id (if exists) will not change in database(it wont add with a new id).
Here is my City class;
[Table("Cities")]
public class City
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
[ForeignKey("Countries")]
public int CountryId { get; set; }
public Country Country { get; set; }
}
And here is my Country class;
[Table("Countries")]
public class Country
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
public ICollection<City> Cities { get; set; }
}
I used CQRS and Mediator design patterns.
This is my Create Command;
public class CreateCityCommand : IRequest<City>
{
public City City { get; set; }
}
This is my Create Command Handler;
public class CreateCityCommandHandler : IRequestHandler<CreateCityCommand, City>
{
private readonly EssoContext _context;
public CreateCityCommandHandler(EssoContext context)
{
_context = context;
}
public async Task<City> Handle(CreateCityCommand request, CancellationToken cancellationToken)
{
var check = await _context.City.FirstOrDefaultAsync(c => c.Name == request.City.Name);
if (check != null)
{
throw new InvalidOperationException("You cannot add the same value!!!");
}
_context.City.Add(request.City);
await _context.SaveChangesAsync();
return request.City;
}
}
And here is my controller;
[HttpPost("Create")]
public async Task<ActionResult<City>> PostCity([FromBody] City city)
{
try
{
var command = new CreateCityCommand() { City = city };
var result = await _mediator.Send(command);
return Ok(result);
}
catch(Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
This is swagger output (seeing countries)
Every city has a country, and each country may have many cities. That's why i used CountryId and property (as FK) in City class. In country class, i defined collection(list) of cities. But I dont know what is the problem. Thanks for help...
CodePudding user response:
As per my understanding you want to get related city data with country
public class GetCountriesCommand: IRequest<IEnumerable<Country>>{
}
public class GetCountriesCommandHandler : IRequestHandler<GetCountriesCommand, IEnumerable<Country>>
{
private readonly EssoContext _context;
public GetCountriesCommandHandler(EssoContext context)
{
_context = context;
}
public async Task<IEnumerable<Country>> Handle(GetCountriesCommand command, CancellationToken cancellationToken)
{
// .Includes helps to return the related cities for all countries
return await _context.Country.Include(x=>x.City).ToListAsync();
}
}
In country controller
[HttpGet("Get-Countries")]
public async Task<IActionResult<IEnumerable<Country>>> Get()
{
try
{
var command = new GetCountriesCommand();
var result = await _mediator.Send(command);
return Ok(result);
}
catch(Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError, ex.Message);
}
}
CodePudding user response:
I guess I figured it out. I just declared CountryId as a foreign key. That's why each CountryId has many cities.
I did city class like that;
[Table("Cities")]
public class City
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(30)]
public string Name { get; set; }
public int CountryId { get; set; }
}
Did I correct?