【发布时间】:2014-08-01 09:27:44
【问题描述】:
注意:我对 C# .Net MVC 和 Entity Framework 还很陌生,并且正在开发一个现有项目。在这个项目中,我有以下课程:
public class MyDbContext : DbContext, IMyDbContext
{
public MyDbContext() : base("name=SQLAzureConnection")
{
}
... // Some IDbSet properties
... // Some methods
}
还有如下界面:
public interface IMyDbContext
{
... // Some properties
... // Some methods
void Dispose();
}
在我使用的一种方法中:
using(IMyDbContext usingDb = MvcApplication.dbContext())
{
// Some query with usingDb
}
(MvcApplication.dbContext() 是一个委托(Func),它在我的 MvcApplication` 中像这样实例化:
public class MvcApplication : System.Web.HttpApplication
{
// Delegate Func to create a new IMyDbContext instance
public static Func<IMyDbContext> dbContext;
public static MyDbContext dbContextInit()
{
return new MyDbContext();
}
... // Some other fields
protected void Application_Start()
{
...
dbContext = dbContextInit();
}
}
我有这个委托的原因是为了短暂的 DbContext 并且能够在我的单元测试中使用它。)
由于使用中的对象应该是Disposable,所以我修改了我的界面如下:
public interface IMyDbContext : IDisposable
{
... // Some properties
... // Some methods
void Dispose();
}
一切正常,除了我收到以下警告:
'MyNamespace.Model.IMyDbContext.Dispose()' hides inherited member
'System.IDisposable.Dispose()'. Use the new keyword if hiding was intended.
这是否意味着我应该使用:new void Dispose(); 而不是 void Dispose()?我让它继承IDisposable 的唯一原因是我可以在using 中使用它。所以我猜new-keyword 所以它会使用DbContext.Dispose() 是处理这个的正确方法吗?还是我做错了什么?
我还读过我可以只使用try-finally 而不是using,所以我自己在finally-case 中使用usingDb.Dispose()。不过,我更喜欢自己继承 IDisposable 而不是那个选项。
【问题讨论】:
标签: c# asp.net-mvc entity-framework inheritance multiple-inheritance