Asp.net-Mvc

Entity Framework Core 可為空的外鍵

  • October 27, 2016

我無法獲取外鍵值可能為空的實體列表。

模型:

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:

聯繫人表

我正在使用實體框架核心 1.0.0。任何幫助將不勝感激。

假設它確實返回了 mary,您希望她的 CompanyId 是什麼?我會懷疑 null (它還能是什麼?),在這種情況下你的模型是錯誤的, public int CompanyId { get; set; } 應該是 public int? CompanyId { get; set; }

引用自:https://stackoverflow.com/questions/40291466