[英]Entity Framework join across two databases
I have a WebAPI. 我有一个WebAPI。 I need to return a list of
ActivityRegisters
. 我需要返回
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
. 但是,
ActivityRegister
表上有一个可为空的列,称为roomID
。 There is a Rooms table but it is in a different database which we have a AdminDBContext
for. 虽然有一个Rooms表,但是它在另一个数据库中,该数据库具有
AdminDBContext
。 I need the API to return the roomName
in the payload which exists in the Admin DB. 我需要API返回管理数据库中存在的有效负载中的
roomName
。 How can I get the above method to return the the roomName
using the roomID
? 如何获得上述使用
roomID
返回roomName
的roomID
? Thank you, I'm new and learning. 谢谢,我是新来的,正在学习。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.