0

I have data structure like this

public class Author
{
    ...
}

public class Comment
{
    public long Userid { get; set; }
    ...
}

public class Blog
{
    public Author Author { get; set; }

    public ICollection<Comment> Comments { get; set; }
}

When i try to retrieve some data from DB i use following construction

IRepository<Blog> blogsRepository = _repositoryFactory.Create<Blog>();
IQueryable<Blog> blogsQuery = blogsRepository.Query().Include(x => x.Author);
List<BlogsData> blogsData = blogsQuery.Select(x => new BlogsData
                                                        {
                                                            Blog = x,
                                                            Commented = x.Comments.Any(z => z.Userid == userId)
                                                        }).ToList();

where BlogsData is

public class BlogsData
{
    public Blog Blog { get; set; }

    public bool Commented { get; set; }
}

But after all data was fetched to List<BlogsData> the Blog.Author property is null.

I don't understand, why Include(x => x.Author) is ignored in this case? And how to get around this problem?

Maxim
  • 1,413
  • 2
  • 10
  • 15
  • 2
    Sometimes when EF is projecting elements, if `.Include()` is not the last statement, some other statements will prevent the include from working (that has been my experience). – Erik Philips Mar 06 '16 at 17:33

1 Answers1

1

Good day, my experience in EF is you need also to add it in select

add Author in

public class BlogsData
{
    public Author Author { get; set; }

    public Blog Blog { get; set; }

    public bool Commented { get; set; }
}

and add it in

List<BlogsData> blogsData = blogsQuery.Select(x => new BlogsData
                                                    {
                                                        Author x.Author,
                                                        Blog = x,
                                                        Commented = x.Comments.Any(z => z.Userid == userId)
                                                    }).ToList();
Gabriel Llorico
  • 1,783
  • 1
  • 13
  • 23