实体框架code首先,不同的上下文/数据库之间的导航属性上下文、实体、框架、属性

2023-09-06 16:28:51 作者:何必太在乎你

您好我有一个映射在一个SQL Server数据库不同的模式,但我需要创建1自卫队数据库文件(SQL精简)每个模式,并使用相同的数据上下文,我有这样的相关的一些实体2数据上下文

Hi I have 2 data contexts that maps different schemas on a SQL Server database, but then I need to create 1 sdf database file (SQL Compact) per schema and use the same data contexts, and I have some entities related like this:

//context 1
class A
{
    int Id
    ...
    ICollection<B> Bs
}

//context 2
class B
{
    int Id
    ...
}

在服务器很容易,我只需要指定表的这种关系,但在客户端上我有这样的实体分裂在不同的数据库。

On server it's easy I just need to specify the table for this relation, but on clients I have this entities splitted on different databases.

所以,我需要从上下文1实体(A)导航属性(database_A.sdf)以涉及与上下文2(database_B.sdf)1实体(B)。

So I need a navigation property on 1 entity (A) from context 1 (database_A.sdf) to relate with 1 entity (B) from context 2 (database_B.sdf).

在此先感谢。

推荐答案

您实现这些类不是上下文这些都是实体。在EF应该在上下文中继承的ObjectContext或的DbContext,你的情况我认为你必须在2个不同的数据库2个独立的实体。你可以这样做是为了指向多个数据库

Those classes you are implemented are not Contexts those are Entities. The Context in EF should inherit from ObjectContext or DbContext, In your case I think you have 2 separate Entities in 2 different Database. You can do this to pointing several database

// Associate with first entity
public Context1 : ObjectContext
{
    prop IDbSet<A> ADbSet{ get; set; }
    ...
}

// Associate with Second entity
public Context2 : ObjectContext
{
    prop IDbSet<B> BDbSet{ get; set; }
    ...
}

public void ChangeDb(string dbName)
{
    Context1 context = new Context1();
    context.ChangeDatabase(dbName);
}

希望这有助于。

Hope this help.