简体   繁体   中英

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

I have the following entities:

public class Seminar
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

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

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

and

public class Meeting
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    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; }
}

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

The ThirdPartyId 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 Title and Description 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

    db.SaveChanges();
}

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

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.

Once you add the entity object to the corresponding DbSet , you can load any reference property by using Load method like this:

Meeting meeting = new Meeting
{
    SeminarId = 5 // this would normally be loaded from elsewhere, obviously
};
db.Meetings.Add(meeting);
// meeting.Webinar is still null
db.Entry(meeting).Reference(m => m.Webinar).Load();
// meeting.Webinar is populated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM