我有一个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
?谢谢,我是新人,也在学习。
答案 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();
}