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();
}
Member
4 Points
10 Posts
Cannot implicitly convert type error
May 19, 2020 12:50 PM|systemthreep|LINK
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
Model
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
Participant
1861 Points
2836 Posts
Re: Cannot implicitly convert type error
May 19, 2020 02:06 PM|EnenDaveyBoy|LINK
Author.Country and AuthorDTO.CountryDTO
are not the same class so you have to map it as well
Member
4 Points
10 Posts
Re: Cannot implicitly convert type error
May 19, 2020 02:18 PM|systemthreep|LINK
Thats right . Please can you advise me how it map Author.Country and AuthorDTO.CountryDTO
Participant
1861 Points
2836 Posts
Re: Cannot implicitly convert type error
May 19, 2020 02:30 PM|EnenDaveyBoy|LINK
something like