我无法获取外键值可能为null的实体列表。
模特:
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; }
}
当我尝试获取所有Contacts
的列表并且其中一个在我的数据库中具有CompanyId
的空值时,它将跳过它返回的列表中的Contact
。例如,查询var contacts = _context.Contacts.Include(c => c.Company).ToList();
仅返回下表中的Josh Stone:
我正在使用Entity Framework Core 1.0.0。任何帮助都将深表感谢。
答案 0 :(得分:10)
假设它实际上确实归来了玛丽,你会期望她的公司是什么?我怀疑是null(它还能做什么?),在这种情况下你的模型是错误的
public int CompanyId { get; set; }
应该
public int? CompanyId { get; set; }