Click here to Skip to main content
16,021,125 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Hi All,

I am having a lot of trouble with this and been investigating many many hours, so I am completely stuck.

I followed the tutorial in the page:
Getting Started on UWP - New Database - EF Core | Microsoft Docs
This is to create a SQLite database and be able to use it in UWP with EntityFrameworkCore.

Until here everything works as intended.
But... I am not able to use the
public List<Post> Posts { get; set; }

When I try to use it, I get the error:
'Object reference not set to an instance of an object.'

But I tried to initialize the object in several ways, and cannot make it work.

I would say that the obvious approach is this:
var blog = new Blog { Url = "theurl", Posts = new List<Posts>() };
db.Blogs.Add(blog);
var thebest = new Post{ Title = "MyTest"};
db.Blogs.SingleOrDefault(x => x.Url == "theurl").Posts.Add(thebest);


But I am in a loop of:
'Object reference not set to an instance of an object.'


I think that the problem is when I am using SingleOrDefault or FirstOrDefault etc etc... it returns a reference? and not the original?
What is the correct way to use this list inside the DbContext?

What I have tried:

Looking and looking in the internet.

Initialize the variables in several different ways.
var blog = new Blog { Url = "theurl", Posts = new List<Posts>() };
db.Blogs.Add(blog);
var thebest = new Post{ Title = "MyTest"};
db.Blogs.SingleOrDefault(x => x.Url == "theurl").Posts.Add(thebest);


var blog = new Blog { Url = NewBlogUrl.Text };
db.Blogs.Add(blog);
db.Blogs.SingleOrDefault(x => x.Url == NewBlogUrl.Text).Posts = new List<Post>();


Always same exception.
Posted
Updated 19-Feb-18 8:00am
v5
Comments
Richard Deeming 16-Feb-18 13:24pm    
Try marking the Posts property as virtual.
Scolo 17-Feb-18 4:37am    
Hi Richard, thanks for the answer :)

tried
public virtual List<Post> Posts { get; set; }

same issue
'Object reference not set to an instance of an object.'

Collections in Entity Framework are exposed as DbSet collections.
 
Share this answer
 
Comments
Scolo 16-Feb-18 10:26am    
Can you be a bit more specific, for example, write a few lines of code where you add an object to the list? thanks,
According to this:
Lazy loading is not yet supported by EF Core. You can view the lazy loading item on our backlog[^] to track this feature.

You will need to use one of the eager / explicit loading options shown on that page instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900