简体   繁体   中英

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.

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;

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();

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM