So I have the following linq query for a test blog:
var random = new Random();
var random = context.Blog.OrderBy(x => random.Next())
.Where(x => x.DisplayStatus == "Approved")
.Select(x => new Blog
{
Title = x.Title,
Content = x.Content,
AuthorId = x.AuthorId,
Author = x.Authors.AuthorName //null pointer exception here
}).Take(5).ToList()
The trouble is, it throws a null pointer exception when it hits 'x.Authors.AuthorName'. I cannot figure out why. I know the author is there because it works fine when I use linq expressions (from x in context.Blog ...etc), and it works in LinqPad. I can't use the linq expression, though, because I don't know how to declare 'OrderBy(x => random.Next())' without using a lambda expression.
this is the version that works without the random
var working = (from x in context.Blog
//NO known code to select random
where x.DisplayStatus == "Approved"
select new Blog
{
Title = x.Title,
Content = x.Content,
AuthorId = x.AuthorId,
Author = x.Authors.AuthorName //NO null pointer exception
}).Take(5).ToList()
Blog is a POCO class with no database relations. Authors is a database entity class with AuthorName being a simple string. Any idea on what is going on here?