I have two Entity Framwork database contexts, one for my application and another for an existing GIS database. My application is an incident tracker where each incident might have an associated GIS address. I've not worked with multiple database contexts before so I'm having a hard time wrapping my head around how best to model this relationship. What I'm picturing is I'd create the class for the incident and GIS address and have a navigation property from the incident to the address.
public class Incident
{
public int Id{ get; set; }
...
public virtual GisAddress? GisAddress{ get; set; }
}
Because they are from different contexts I've gathered the incidents and addresses separately.
List<Incident> incidents = await _trackerContext.Incident
.AsNoTracking()
.ToListAsync();
List<GisAddress> addresses = await _gisContext.Addresses
.Where(x => incident.Select(l => l.GisAddId).Contains(x.AddId))
.AsNoTracking()
.ToListAsync();
And it's at this point that I would like to setup that navigation property on the incident. I'm not sure if I should do this through a join or if these is some different EF specific loading I can configure to map that relationship? But the goal is that when I go to say list them out I can do:
@Html.DisplayFor(modelItem => i.GisAddress.FullAddress)
Is this the correct way to approach creating a relationship in EF Core between related tables in different databases?
So far I've tried creating a new class with a property for both incidents and address but that doesn't seem correct and I'm concerned that the maintenance of setting of these different view models would become too much.
public class IncidentGisAddressViewModel
{
public Incident Incident { get; set; }
public GisAddress GisAddress { get; set; }
}
CodePudding user response:
You can join local collections on the client side:
var query =
from i in incidents
join a in addresses on i.GisAddId equals a.AddId
select new IncidentGisAddressViewModel
{
Incident = i,
GisAddress = a
};
var result = query.ToList();