Answered by:
Cannot implicitly convert type error

Question
-
User2038750770 posted
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; } }
ModelAuthorDTO 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(); }
Tuesday, May 19, 2020 12:50 PM
Answers
-
User1034446946 posted
something like
authorsDto.Add(new AuthorDto { AuthorId = author.AuthorId, FirstName = author.FirstName, LastName = author.LastName Country = new CountryDTO{ Name = author.Country.Name //other fields here} });
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, May 19, 2020 2:30 PM
All replies
-
User1034446946 posted
Author.Country and AuthorDTO.CountryDTO
are not the same class so you have to map it as well
Tuesday, May 19, 2020 2:06 PM -
User2038750770 posted
Thats right . Please can you advise me how it map Author.Country and AuthorDTO.CountryDTO
Tuesday, May 19, 2020 2:18 PM -
User1034446946 posted
something like
authorsDto.Add(new AuthorDto { AuthorId = author.AuthorId, FirstName = author.FirstName, LastName = author.LastName Country = new CountryDTO{ Name = author.Country.Name //other fields here} });
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, May 19, 2020 2:30 PM