简体   繁体   English

是否可以在Entity Framework中将外键急于加载到新对象上?

[英]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). Meeting通过SeminarId属性(外键)与Seminar相关。

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. 在调用第三方API之后,将填充ThirdPartyId属性(名称更改为保护我的利益)-这是该系统的“链接”。

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. 为了进行此调用(在该系统中我们在该系统上创建相同的对象),我们需要与会议相关联的研讨会的“ Title和“ Description信息。

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 . 我想做的是在调用第三方API或SaveChanges之前在meeting上加载外键属性。 Is this possible? 这可能吗?

Simply call the database for the Seminar by its id and Assign it to the meeting like Meeting.Seminar = dbSeminar . 只需通过ID为其调用研讨会数据库,并将其分配给会议,例如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. 为了回答您的评论, virtual只是说此方法/属性可能被继承类覆盖,并且当ref为基类类型时 ,只要实际类型为继承类,则重写该方法/属性以使用继承类的prop /方法。

Once you add the entity object to the corresponding DbSet , you can load any reference property by using Load method like this: 将实体对象添加到相应的DbSet ,可以使用如下所示的Load方法加载任何引用属性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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