简体   繁体   中英

Entity Framework Orderby One to Many Entity

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; }
}

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)

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