My mode class and modelDTO is given below. When I am trying to assign an object entity to another object entity the error is coming Please help in my code
Author
public class Author { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int AuthorId { get; set; } [Required] [MaxLength(100, ErrorMessage ="First Name cannot be more than 100 characters")] public string FirstName { get; set; } [Required] [MaxLength(200, ErrorMessage = "Last Name cannot be more than 200 characters")] public string LastName { get; set; } [ForeignKey("CountryId")] public int CountryId { get; set; } public Country Country { get; set; } }
Model
AuthorDTO public class AuthorDto { public int AuthorId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int CountryId { get; set; } public CountryDto Country { get; set; } public IEnumerable<SelectListItem> CountryList { get; set; } }
public IActionResult GetAuthors()
{
var authors = _authorRepository.GetAuthors();
if (!ModelState.IsValid)
return BadRequest(ModelState);
var authorsDto = new List<AuthorDto>();
foreach (var author in authors)
{
authorsDto.Add(new AuthorDto
{
AuthorId = author.AuthorId,
FirstName = author.FirstName,
LastName = author.LastName
Country = author.Country // Here error is coming 'Cannot implicitly convert type error'
});
}
GetAuthor Method
public ICollection<Author> GetAuthors() { var authorList = _db.Authors.Include(c => c.Country).ToList(); }