C#继承的铸造成员
我正在为我的实体框架数据库上下文类的基类工作。在基类中,我需要访问DbContext,并且在派生类中,我需要访问派生的DbContext。目前我有以下代码:C#继承的铸造成员
public abstract class BaseClass: IDisposable
{
protected abstract DbContext BaseContext { get; }
public void Dispose()
{
if (BaseContext != null)
{
BaseContext.Dispose();
}
}
}
public class DerivedClass : BaseClass
{
DerivedContext context; // public class DerivedContext: DbContext
protected override DbContext BaseContext
{
get
{
return context;
}
}
}
这是一个正确的方法吗?
我建议更多的东西一样
public abstract class BaseClass<TContext> : IDisposable
where TContext : DbContext
{
//not abstract
protected TContext Context { get; private set; }
}
public class DerivedClass : BaseClass<DerivedContext>
{
....
}
在你的基类,你可以访问所有你DerivedClass的DbContext的成员,并可以访问所有DerviedContext的成员,而不需要转换。
它在某种程度上取决于你期望如何使用它。您发布的代码将始终将派生上下文与派生类的实例以及基类的基本上下文一起使用。
// This code gets an instance of the DerivedContext.
BaseClass myBase = new DerivedClass();
DbContext myContext = myBase.BaseContext;
如果这是您打算如何工作,您正在使用正确的方法。
您不希望取决于dbcontext的域对象。该域应该不知道dbcontex。 回答你的问题:不,这不是“正确的”。
你可能拥有的是一系列围绕使用dbcontext加载/保存实体的域对象分层的组件。
我不知道为什么你认为BaseClass和DerivedClass是域对象。这个问题似乎并没有表明这一点。 – cadrell0 2012-01-06 14:01:57
@ cadrell0第二次阅读OP,你的权利。由于'@ Jani'留下的关于AR的评论,我假定了一个域对象。 – 2012-01-06 16:22:29
根据您需要在派生类中做些特别的事情需要多少时间,您也可以首先使用通用方法。从这里你也可以继承。
public class BaseClass<TContext> : IDisposable
where TContext : IContext
{
public TContext Context { get; private set; }
public void Dispose()
{
if (Context != null)
{
Context.Dispose();
}
}
public BaseClass(TContext context)
{
this.Context = context;
}
}
public interface IContext : IDisposable
{
}
public ChildClass : BaseClass<MyContext>
{
public ChildClass(MyContext context)
: base(context)
{
}
}
至少您的IDisposable
实现必须改进。你应该做如下:
IDisposable
例如:
public class BaseClass : IDisposable
{
private bool _disposed = false;
protected DbContext Context { get; }
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this._disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Disposes managed resources here
if (this.Context != null)
{
this.Context.Dispose();
}
}
// Disposes unmanaged resources here
// NOTHING HERE
// Note disposing has been done.
this._disposed = true;
}
}
}
对于DBContext
本身,这取决于你打算如何使用它。
你为什么这样做?我想你想要实现的是类似于http://www.castleproject.org/activerecord/ – 2012-01-06 13:38:32