实体框架核心可为空的外键 [英] Entity Framework Core nullable foreign key
问题描述
我在获取外键值可能为空的实体列表时遇到了麻烦.
I am having trouble getting a list of entities where a foreign key value could be 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:
When I try and get the list of all Contacts
and one of them has a null value for CompanyId
in my database, it will skip that Contact
in the list it returns. For example, the query var contacts = _context.Contacts.Include(c => c.Company).ToList();
only returns Josh Stone from the following table:
我正在使用Entity Framework Core 1.0.0.任何帮助将由衷的感谢.
I am using Entity Framework Core 1.0.0. Any help would be sincerely appreciated.
推荐答案
假设它确实返回了mary,您希望她的CompanyId是什么?我会怀疑为null(还可能是什么?),在这种情况下,您的模型是错误的,
public int CompanyId { get; set; }
应该
public int? CompanyId { get; set; }
Supposing that it did actually return mary, what would you expect her CompanyId to be? I would suspect null (what else could it be?), in which case your model is wrong and
public int CompanyId { get; set; }
should be
public int? CompanyId { get; set; }
这篇关于实体框架核心可为空的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!