我见过类似的,但找不到答案。我有 2 个实体出版物和作者。作者不是强制性的,当我 OrderBy Publication.Author.Surname 我得到 NullReferenceException 因为出版物总是有相关的作者。我该如何编写这个简单的查询,为什么 EhtityFramework 知道如何处理这个问题?
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();
失败是因为出版物并不总是有相关的作者。注意:db 是实体框架 DBContext,如下所示:
public class PPRDBContext : DbContext
{
public DbSet<Publication> Publications { get; set; }
public DbSet<Author> Authors { get; set; }
}