How can I use EF Core to display data from 3 different tables in my application

Viewed 50

I have 3 different tables, Customer, Vehicle, Contact.

The customer and vehicle tables share the common key ReferenceID and the customer and contact table share the key ContactID.

I want to be able to use EF core to display data from all three tables and was wondering if there is a way to do it without using JOIN?

Below is my attempt but I get this error: SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

public class Customer
{
    public string Name { get; set; }
    [ForeignKey("Vehicle")]
    public string ReferenceID { get; set; }
    [ForeignKey("Contact")]
    public string ContactID { get; set;}
    public ICollection<Contact> Contact { get; set; }
    public ICollection<Vehicle> Vehicle { get; set; }
}

public class Vehicle
{
    public string ReferenceID { get; set;}
    public string Make {get; set;}
}

public class Contact
{
    public string ContactID {get; set;}
    public string Name {get; set;}
}
1 Answers

You don't need the JOINS here, You already have the access to the other tables as Navigation Property. If you are not using the Lazy loading the properties Vehicle and Contact will load their data.

If the values didn't get load, you can load them as below.

var customers = _context.Customers.Include("Contact").Include("Vehicle");
Related