Brian Gradin Brian Gradin - 1 year ago 60
C# Question

Is it possible to eagerly load the foreign key on a new object in Entity Framework?

I have the following entities:

public class Seminar
public int Id { get; set; }

public string Title { get; set; }
public string Description { get; set; }

public virtual List<Meeting> Meetings { get; set; }


public class Meeting
public int Id { get; set; }

public int SeminarId { get; set; }
public string ThirdPartyId { get; set; }
public DateTime StartDate { get; set; }

public virtual Webinar Webinar { get; set; }

is related to
by the
property (a foreign key).

property (name changed to protect my interests) is populated after making a call to a third party API - it's the "link" to that system.

In order to make this call (in which we create the same object on that system), we need the
information from the seminar associated with the meeting.

So let's say I create a new meeting like so:

using (var db = new MyDbContext())
Meeting meeting = new Meeting
SeminarId = 5 // this would normally be loaded from elsewhere, obviously

// Load the meeting.Webinar property somehow here

m_thirdPartyApiClient.CreateMeeting(meeting); // Uses meeting.Webinar.Title and meeting.Webinar.Description


What I'd like to do is to load the foreign key property on
before calling the third party API or
. Is this possible?

Answer Source

Simply call the database for the Seminar by its id and Assign it to the meeting like Meeting.Seminar = dbSeminar. To answer your comment, virtual just says that this method/property may be over written by a inheriting class and when overwritten to use the inheriting class's prop/method even when the ref is of type base class as long as the actual type is inheriting class.