Entity Framework Core 2.0: One-To-Many-Relationship only works once

asp.net-core c# entity-framework-core entity-relationship

Question

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?

1
1
2/27/2018 9:59:40 AM

Popular Answer

I believe that you have not fully defined the relationship between the two models. Based on this documentation

Relationships

You are missing the link from Word back to Vocabulary. Adding this to the Word class should solve it:

public int VocabularyId {get; set; }
0
2/27/2018 11:25:38 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow