我有2个独立的数据库,因此在ASP.Net Core / EFCore中有2个独立的DbContext。
我有一个在一个数据库中的对象,它有一个指向另一个数据库的“外键”。
假设我有一个充满事件的数据库,另一个有城市的地理数据库。我的活动课上有一个cityId。
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;}
}
在查询第一个DbContext时,是否有可能以某种方式Include
City属性?
不,这是不可能的,你必须独立查询其他上下文。
var event = eventContext.Events.Find(eventId);
event.City = geoContext.Cities.Find(event.CityId);
FWIW,你应该把City
上的Event
财产标记为NotMapped
。否则,EF将在与Cities
相同的数据库中创建一个Events
表,并在Events
上向该表添加一个实际外键,即使City
实际上是由不同的上下文管理。
Dbcontext是数据库的一些范围!
你只能存储一些int值!没有导航属性!
因为数据库中的所有外键都无法引用另一个数据库! Ef核心是对数据库的一些抽象!许多RDBms不允许外键到另一个数据库!
你可以触发一些诚信! Add Foreign Key relationship between two Databases
这是一个不好的做法!