I'm using ASP.NET Core 2.0 with Angular-Frontend and Entity Framework Core 2.0. I have following DbSets: DbSet<Vocabulary> Vocabularies
and DbSet<Word> Words
, while the class Vocabulary
contains a collection of words: List<Word> Words { get; set; }
. In my API-Controller I've written a method which provides the vocabularies to the frontend as a response to an HTTP-Get-request. To test my database-connection and everything, I used the same method to create an initial record into my database:
[HttpGet]
public IEnumerable<Vocabulary> Get()
{
if (!Context.Vocabularies.Any())
{
Context.Vocabularies.Add(new Vocabulary
{
Name = "MyVocabulary",
Words = new List<Word>
{
new Word
{
PrimaryLanguage="Test",
SecondaryLanguage="Test",
Score= 0
}
}
});
Context.SaveChanges();
}
return Context.Vocabularies;
}
Now, the weird thing is that when the DB is empty, everything works as expected. When I reload the page (or restart the local IIS) and the HTTP-GET-request happens again, I get all vocabularies with correct ID's etc. but the property Words
is null... I'm using a local SQL Server database. The tables seem ok, the words have the correct VocabularyId
.
I just found out that there's a method called Include()
. Tried it the following way: return Context.Vocabularies.Include(v => v.Words);
, but didn't work either.
Vocabulary.cs:
public class Vocabulary
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Word> Words { get; set; }
}
Word.cs:
public class Word
{
public int Id { get; set; }
public string PrimaryLanguage { get; set; }
public string SecondaryLanguage { get; set; }
public double Score { get; set; }
}
Any ideas?
I believe that you have not fully defined the relationship between the two models. Based on this documentation
You are missing the link from Word back to Vocabulary. Adding this to the Word class should solve it:
public int VocabularyId {get; set; }