User2038750770 posted
Hi
I have two table Authors and Country. Country is the foreign key table of Author. When list authors , the corresponding country is not being showed. Please help in my sql
Country table
CountryId CountryName
1 UK
2 Australia
Authors
AuthorId FirstName LastName CountryId
1 Thomas Philiph 1
2 John Varghese 2
Model
public class Country
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CountryId { get; set; }
[Required]
[MaxLength(50, ErrorMessage = "Country must be up to 50 characters in length")]
public string CountryName { get; set; }
[JsonIgnore]
public virtual ICollection<Author> Authors { get; set; }
}
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; }
}
Repository. When I try to list all the Authors with their country details, the country is being showed as null. How can I list the related country records also with their details
public class AuthorRepository : IAuthorRepository
{
private BookStoreDbContext _db;
public AuthorRepository(BookStoreDbContext db)
{
_db = db;
}
public ICollection<Author> GetAuthors()
{
var authorlist = _db.Authors.OrderBy(a => a.LastName).ToList(); // Country is not showed here
return authorlist
}
}