首页 > 解决方案 > 如何将 DbContext 转换为 MyContext

问题描述

我有一个带有属性 DbContext Db 的接口。然后,我有一个实现这个接口的类。在那个类中,我想将 MyContext 分配给属性 Db。这可行,但我不能将 Db 转换为 MyContext。我应该如何正确制作这个演员?

public interface ILine
{
    DbContext Db { get; }
}
public class Line: ILine
{
    public DbContext Db { get; private set; }

    public int SomeMethod()
    {
        using(Db = new MyContext()){
        //var temp = (MyContext)Db.rall.where(p=>p.id = 1).count();
        // Line above cant be compiled, .rall is underlined, is specific for MyContext
        }
    }
}

标签: c#entity-frameworkdbcontext

解决方案


如果你的上下文没有协变和逆变问题 http://tomasp.net/blog/variance-explained.aspx/ 你可以这样使用

    (Db  as MyContext).rall.where(p=>p.id = 1).count();

推荐阅读