2

I have 2 separate databases, and therefore 2 separate DbContext in ASP.Net Core/EFCore.

I have an object that is in one database, which has a "foreign key" which points on another database.

Let's say I have a database filled with events, and another geographic database with cities. I have a cityId on my event class.

public class Event
{
  public int Id {get;set;}
  public string Name {get;set;}
  public string CityId {get;set;}
  public virtual City City {get;set;}
}

public class City
{
  public int Id {get;set;}
  public string Name {get;set;}
}

Is it possible to Include the City property in some way when querying the first DbContext?

Jean
  • 4,911
  • 3
  • 29
  • 50

2 Answers2

5

No. It's not possible, you'll have to independently query the other context.

var event = eventContext.Events.Find(eventId);
event.City = geoContext.Cities.Find(event.CityId);

FWIW, you should mark the City property on Event as NotMapped. Otherwise, EF will create a Cities table in the same database as Events and add an actual foreign key to that table on Events, even though City is actually being managed by a different context.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
-1

Dbcontext is some scope of database !

You could only store some int value! Without navigation property!

Because all foreign keys in database could not referenced to another database! Ef core is some abstraction over database! Many RDBms dos not allowed foreign keys to another database!

U could make a trigger to make some kind of integrity! Add Foreign Key relationship between two Databases

It is a not good practice!

Diaskhan
  • 11
  • 2