实体框架核心可以为空的外键

时间:2016-10-27 18:09:29

标签: asp.net-mvc entity-framework-core

我无法获取外键值可能为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:

Contacts Table

我正在使用Entity Framework Core 1.0.0。任何帮助都将深表感谢。

1 个答案:

答案 0 :(得分:10)

假设它实际上确实归来了玛丽,你会期望她的公司是什么?我怀疑是null(它还能做什么?),在这种情况下你的模型是错误的 public int CompanyId { get; set; }  应该 public int? CompanyId { get; set; }