user3788648
user3788648

Reputation: 31

Linq query returns null when using the EF core relationship

Two class defined as below :

class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; set; }
}
class Post
{
     public int PostId { get; set; }
     public string Title { get; set; }
     public string Content { get; set; }

     public int BlogId { get; set; }
     public Blog Blog { get; set; }
}

and when using this Linq query :
var posts = context.Blog.FirstOrDefault(e => e.BlogId == 1).Posts.ToList();
an exception is thrown which says value cannot be null. And in result view the Posts column of the Blog Table for each row is empty.

Upvotes: 0

Views: 3126

Answers (3)

Shantanu
Shantanu

Reputation: 554

As there is no lazy loading you need to include the entity Posts

var blog = context.Blog
                   .Include(b => b.Posts)
                   .FirstOrDefault(e => e.BlogId == 1);

as you are doing Firtordefault you need to check for null

if(blog != null)
{
  ... do your work
}

Upvotes: 1

Pribina
Pribina

Reputation: 780

Try to rewrite query FirstOrDefault causes querying db and therefore relationship might not be loaded

Therefore do projection before querying:

var posts = context.Blog
                   .SelectMany(b => b.Posts)
                   .Where(p => p.BlogId == 1)
                   .ToList();

Other alternative is to use .Include()

var posts = context.Blog
                   .Include(b => b.Posts)
                   .FirstOrDefault(e => e.BlogId == 1)
                   ?.Posts;

Upvotes: 3

Thili
Thili

Reputation: 788

It's better if you can include select clause here. Calling FirstOrDefault() on your query will return the first result of the query or the default value for the type (most likely null in this case). try out this

var posts =
    (from e in context.Blog
    where e.BlogId == 1
    select e).FirstOrDefault();

Upvotes: 1

Related Questions