Reputation: 481
I've seen similar to this but cant find an answer. I have 2 enities Publication and Author. Author is NOT mandatory and when I OrderBy Publication.Author.Surname I get NullReferenceException because a Publication dosnt always have a related Author. How do I write this simple query and why the heck dosnt EhtityFramework know how to deal with this?
public class Publication {
[Key]
public int ID { get; set; }
public string Title { get; set; }
[Display(Name = "Author")]
public int? AuthorId { get; set; }
public virtual Author Author { get; set; }
}
public class Author{
[Key]
public virtual int ID { get; set; }
public virtual string Forename { get; set; }
public virtual string Surname { get; set; }
}
this.db.Publications
.OrderBy(p=>p.Author.Surname)
.Skip(skip)
.Take(model.PageSize).ToList();
Fails because a Publication dosnt always have a related Author. Note: db is the Entity Framework DBContext as below:
public class PPRDBContext : DbContext
{
public DbSet<Publication> Publications { get; set; }
public DbSet<Author> Authors { get; set; }
}
Upvotes: 0
Views: 295
Reputation: 152511
It's not EF's fault - it's a common trap with any language I know of when accessing properties of referenced objects.
Depending on whether you want NULL values to come first you could do something like:
.OrderBy(p=> p.Author == null ? "" : p.Author.Surname)
If you want the NULL values to come last use something like:
.OrderBy(p=> p.Author == null ? "ZZZZZ" : p.Author.Surname)
Upvotes: 3