实体框架跨两个数据库连接

时间:2015-07-14 17:37:11

标签: c# linq entity-framework join

我有一个WebAPI。我需要返回ActivityRegisters的列表。我们有一个存储库就是这样的:

public IQueryable<ActivityRegister> GetRegisters(int activityID) 
{
    return ActivityDBContext.ActivityRegisters.Where(x => x.ActivityID == activityID x.IsActive == true).OrderBy(x => x.ActivityRegisterID).AsQueryable();
}

但是,ActivityRegister表上有一个名为roomID的可空列。有一个Rooms表,但它位于一个不同的数据库中,我们有一个AdminDBContext。我需要API来返回Admin DB中存在的有效负载中的roomName。如何使用roomName获取上述方法以返回roomID?谢谢,我是新人,也在学习。

1 个答案:

答案 0 :(得分:2)

您可以跨两个不同的上下文对表执行连接,如下所示:

public IQueryable<ActivityRegister> GetRegisters(int activityID) 
{
    var activityRegisters = ActivityDBContext.ActivityRegisters.Where(x => x.ActivityID == activityID x.IsActive == true).OrderBy(x => x.ActivityRegisterID).ToList();
    var roomIdsFromActivityRegisters = activityRegisters.Select(activityRegister => activityRegister.roomID);
    var rooms = AdminDBContext.Rooms.Where(room => roomsIdFromActivityRegisters.Contains(room.Id)).ToList();
    var resultFromJoinAcrossContexts = (from activityRegister in activityRegisters 
                                        join room in rooms on activityRegister.roomID equals room.Id
                                        select new ActivityRegister
                                        {
                                            Room = room,
                                            roomID = room.Id,
                                            Id = activityRegister
                                         });
    return resultFromJoinAcrossContexts.AsQueryable();
}