c# - 如何将 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
}
}
}
解决方案
如果你的上下文没有协变和逆变问题 http://tomasp.net/blog/variance-explained.aspx/ 你可以这样使用
(Db as MyContext).rall.where(p=>p.id = 1).count();
推荐阅读
- java - 与 Photoshop 手动调整图像大小相比,自动调整图像大小时,ML 模型的准确性较低
- sql - 先选择最大的日期,然后在sql【SQL Server】中选择相关的日期
- webgl - 背景颜色与 COLOR_BUFFER_BIT
- node.js - 反应停留在登录页面而不是重定向到仪表板
- java - 在 libGDX 中刷新 hud
- android - Class.forname(net.sourceforge.jtds.jdbc.driver) 错误
- android - 如何保证AR场景中的卡片四边与手机四边平行?
- ajax - 如何使用 ajax 在刀片中显示验证错误?
- node.js - 最后一次递归调用后追加数据?
- grafana - 如何在 Grafana-Alert-Message 中使用变量?特别是对于“阈值”的值