corsaro
corsaro

Reputation: 773

Web api use ForeignKey return NULL

I create a simple web api 'get' work good, but when i try to add ForeignKey with Relation One-to-Many One Article many ArticleBody the result of API come with article: null, don't return the description of article why?

[
  {
    "id": 4,
    "title": "Fineco - Corporate Business Template",
    "creationDate": "2020-07-18T00:00:00",
    "updateDate": null,
    "images": null,
    "articleId": 3,
    "article": null
  },
]

// GET: api/Articles
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Articles>>> GetArticles()
        {
            return await _context.Articles.ToListAsync();
        }

public partial class Articles
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public DateTime? CreationDate { get; set; }
        public DateTime? UpdateDate { get; set; }
        public string Images { get; set; }
        public int? ArticleId { get; set; }
        
        [ForeignKey(nameof(ArticleId))]
        //[InverseProperty(nameof(ArticlesBody.Articles))]
        public virtual ArticlesBody Article { get; set; }
    }


public partial class ArticlesBody
{
    public ArticlesBody()
    {
        Articles = new HashSet<Articles>();
    }

    public int Id { get; set; }
    public string Article { get; set; }

    public virtual ICollection<Articles> Articles { get; set; }
}

this is part of DBContext for Articles:

entity.Property(e => e.Images) .HasColumnName("images") .HasMaxLength(50) .IsUnicode(false);

            entity.Property(e => e.Title)
                .HasColumnName("title")
                .HasMaxLength(50);

            entity.Property(e => e.UpdateDate)
                .HasColumnName("updateDate")
                .HasColumnType("datetime");

            entity.HasOne(d => d.Article)
                .WithMany(p => p.Articles)
                .HasForeignKey(d => d.ArticleId)
                .HasConstraintName("FK_Articles_ArticlesBody");

        

Upvotes: 0

Views: 723

Answers (1)

verbedr
verbedr

Reputation: 2270

EF Core will not automatically load navigation properties but instead gives you 3 options to load the navigation properties. Loading Related Data

In this case I would use Eager loading method and specify inlcudes for the navigation property you wish to return. Like this

[HttpGet]
public async Task<ActionResult<IEnumerable<Articles>>> GetArticles()
{
    return await _context.Articles.Include(e => e.Article).ToListAsync();
}

Upvotes: 1

Related Questions