-1

I'm trying to learn one to many relations with EF Core.

In summary: I have two tables; Artists and Songs.

But when I try to reach songs which belongs that artist I am getting error.

Why I'm getting null reference error?

enter image description here

enter image description here

enter image description here

Bassie
  • 9,529
  • 8
  • 68
  • 159
Nihil
  • 49
  • 1
  • 2
  • 1
    What is in the value of `theArtist.Songs` ? Maybe you need to do `DB.Artists.Include(a => a.Songs)` to retrieve them from the db – Bassie Oct 30 '21 at 23:27
  • Just curious, how are you getting that shading ? – TheGeneral Oct 30 '21 at 23:35
  • @Bassie The value of `theArtist.Songs` is null. But it's not suppose to be null cuz in the database there is a song that belongs the artist. But `Include` is solved my problem, thank you. – Nihil Oct 30 '21 at 23:44
  • 1
    @TheGeneral It's the dark theme of visual studio 22. But I added a background pic with using ClaudiaIDE extension. – Nihil Oct 30 '21 at 23:46
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Mark Benningfield Oct 30 '21 at 23:50
  • @MarkBenningfield most probably It would but my english is not enough to process that article. – Nihil Oct 30 '21 at 23:55
  • In `Artist` change `public List Songs { get; set; }` to `public List Songs { get; set; } = new List ();` – Tu deschizi eu inchid Oct 31 '21 at 16:56
  • Next time, [please don't post code, exceptions, or results as images](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). They can't be copied (partly) for answering and their "text" won't appear in search engines. Images should only be used as a last resort. – Gert Arnold Oct 31 '21 at 18:54

1 Answers1

1

You have to include the related entity you want in the list manually, include Songs like the following way:

var theArtist = DB.Artists.Include("Songs").FirstOrDefault(a => a.ID==1);
Mamun
  • 66,969
  • 9
  • 47
  • 59