24

I am having trouble getting a list of entities where a foreign key value could be null.

The Models:

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; }
}

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:

Contacts Table

I am using Entity Framework Core 1.0.0. Any help would be sincerely appreciated.

0

1 Answer 1

35

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; }

Sign up to request clarification or add additional context in comments.

2 Comments

I am using mysql as db and with your solution, the foreign key would not set as null, instead with 0. And mysql throw exception that the inserted key can not be find in the related table. How can I solve it??
@HamedHamedi That would be unrelated to the solution. Either you did database first, in which you created the table with a default value, or you did code first, in which case that is set up incorrectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.