加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 实体框架核心可空外键

发布时间:2020-12-16 07:25:43 所属栏目:asp.Net 来源:网络整理
导读:我无法获取外键值可能为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
我无法获取外键值可能为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; }
}

当我尝试获取所有联系人的列表,并且其中一个联系人在我的数据库中具有CompanyId的空值时,它将在它返回的列表中跳过该联系人.例如,查询var contacts = _context.Contacts.Include(c => c.Company).ToList();只返回下表中的Josh Stone:

Contacts Table

我正在使用Entity Framework Core 1.0.0.任何帮助将是真诚的感谢.

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读