Entity Framework join across two databases

白昼怎懂夜的黑 提交于 2020-01-17 01:42:30

问题


I have a WebAPI. I need to return a list of ActivityRegisters. We have a repository that does it like this:

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

However, there is a nullable column on the ActivityRegister table called roomID. There is a Rooms table but it is in a different database which we have a AdminDBContext for. I need the API to return the roomName in the payload which exists in the Admin DB. How can I get the above method to return the the roomName using the roomID? Thank you, I'm new and learning.


回答1:


You can perform a join on tables across two different contexts like this:

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();
}


来源:https://stackoverflow.com/questions/31413578/entity-framework-join-across-two-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!