In my Entity Framework 6 application, I have a table of people's email addresses:
public class EmailAddress
{
public int Id { get; set; }
public int PersonId { get; set; }
public string EmailAddress { get; set; }
public virtual Person Person { get; set; }
}
And the Person object references these email addresses also:
public class Person
{
public int Id { get; set; }
{...}
public virtual ICollection<EmailAddress> EmailAddresses { get; set; }
}
If I want to get all the email addresses for a single person and check whether the person actually exists, would it be more efficient to either:
Run an
Any()query on thePersonstable and then another query on theEmailAddressestable, usingPersonIdas a parameter:public IEnumerable<EmailAddress> GetAddressesByPerson(int personId) { if (!Context.Persons.Any(x => x.Id == personId)) { throw new Exception("Person not found"); } return Context.EmailAddresses.Where(x => x.PersonId == personId).ToList(); }Get the
Personobject and return theEmailAddressesnavigation property:public IEnumerable<EmailAddress> GetAddressesByPerson(int personId) { var person = Context.Persons.Find(personId); if (person == null) { throw new Exception("Person not found") } return person.EmailAddress; }