Ho problemi a ottenere un elenco di entità in cui un valore di chiave esterna potrebbe essere nullo.
I modelli:
public class Company
{
[Key]
[Required]
public int Id { get; set; }
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Display(Name = "Main Phone")]
public string LandPhone { get; set; }
[Display(Name = "Fax")]
public string FaxPhone { get; set; }
}
public class Contact
{
[Key]
[Required]
public int Id { get; set; }
[Display(Name ="First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[EmailAddress]
public string Email { get; set; }
[Display(Name = "Mobile Phone")]
public string MobilePhone { get; set; }
[Display(Name = "Office Phone")]
public string LandPhone { get; set; }
[Display(Name = "Fax")]
public string FaxPhone { get; set; }
public string Title { get; set; }
public int CompanyId { get; set; }
[ForeignKey("CompanyId")]
public Company Company { get; set; }
}
Quando provo a ottenere l'elenco di tutti i Contacts
e uno di essi ha un valore null per CompanyId
nel mio database, salterà quel Contact
nell'elenco che restituisce. Ad esempio, la query var contacts = _context.Contacts.Include(c => c.Company).ToList();
restituisce solo Josh Stone dalla tabella seguente:
Sto usando Entity Framework Core 1.0.0. Qualsiasi aiuto sarebbe sinceramente apprezzato.
Supponendo che in realtà sia tornato Mary, cosa ti aspetteresti che fosse la sua compagnia? Sospetto nullo (cos'altro potrebbe essere?), Nel qual caso il tuo modello è sbagliato e public int CompanyId { get; set; }
dovrebbe essere public int? CompanyId { get; set; }