在实体框架中为多个类似数据库创建通用接口

时间:2018-07-04 13:35:00

标签: c# sql entity-framework ado.net ado

我当前遇到的问题是必须使用彼此非常相似但结构上有些差异的多个数据库。由于遗留原因,无法将数据库更新为全部具有相同的结构。 我当前的项目结构如下:

public DBContextA : DBContext
{
    DBSet<TypeA> TypeA { get; }

    // Other DBSets
}

public DBContextB : DBContext
{
    DBSet<TypeB> TypeB { get; }

    // Other DBSets
}

public interface ICommon
{
    long ID { get; set; }
}

public class TypeA : ICommon
{
    long ID { get; set; }

    // Other Properties
}

public class TypeB : ICommon
{
    long ID { get; set; }

    // Other Properties
}

我现在想从DBContext查询所有ICommons。我当前的代码如下:

// GetContextByConnection gets the context via reflection based on the selected database
using (var context = GetContextByConnection(connection))
{
    return context.Set<ICommon>().ToList();
}

选择正确的数据库可解决DBContext的ConnectionString重载问题,但出现异常

"the entity type ICommon is not part of the model for the current context"

这很有意义。但是问题是如何查询ICommons?

0 个答案:

没有答案