Load properties in other context in Entity Framework Core

asp.net-core entity-framework entity-framework-core

Question

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?

1
2
2/28/2018 12:46:47 PM

Accepted Answer

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.

5
2/28/2018 2:20:12 PM

Popular Answer

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!



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow