Reputation: 710
Hi I am wanting to create a base class to inherit from but I am having some problems.
I have two classes which do almost identical work but get the data which they work with from different databases and use different internal data structures to manipulate the data. I want to have virtual doSomething method in the base and ideally virtual dataAccess method in the base also.
The second problem can be solved through the use of generics but I cant use generics to solve the first problem as the constructor of the DBMl context I use is not parameterless.
Am I going about this all wrong. I am trying to be DRY but seem to be working against inheritance.
Example code below.
class Foo {
private _ctx DBML.Database1; // Inherits from System.Data.Linq.DataContext
public Foo(string constring) {
_ctx = new DBML.Database1(constring);
}
private DoSomeThing() {
FooDataObj = DataAccess(1);
}
private FooDataObj DataAccess(int ID)
{
var v = from t in _ctx
where t.Id = ID
select new FooDataObj(t);
return v
}
}
class Bar {
private _ctx DBML.Database2; // Inherits from System.Data.Linq.DataContext
public Bar(string constring)
{
_ctx = new DBML.Database2(constring);
}
private DoSomeThing() {
BarDataObj = DataAccess(1);
}
private BarDataObj DataAccess(int ID) {
var v = from t in _ctx
where t.Id = ID
select new BarDataObj(t);
return v
}
}
Upvotes: 4
Views: 318
Reputation: 10205
You should make a base class that encapsulates the functionality you want to share. In this case, you could reuse the data access code if you use an interface on your entity object. Something like this:
interface IUniqueEntity
{
int ID { get; }
}
abstract class FooBarBase<TEntity>
where TEntity : class, IUniqueEntity
{
private DataContext _ctx;
public Foo(DataContext context) {
_ctx = context;
}
protected abstract DoSomeThing();
protected TEntity DataAccess(int ID)
{
return _ctx.GetTable<TEntity>()
.First(e => object.Equals(e.ID, ID);
}
}
Then you can apply the IUniqueEntity interface to your Foo/BarDataObj, and inherit your Foo/Bar classes from FooBarBase:
class Foo : FooBarBase<FooDataObj> {
public Foo(DBML.Database1 context) : base(context) {
}
protected override DoSomeThing() {
var myobj = DataAccess(1);
}
}
Upvotes: 0
Reputation: 20044
Foo
and Bar
should not call the database constructor by themselves, the database object should be a parameter of the constructor (instead of the connection string). This principle is called Dependency Injection and will solve most of your problems. Should be easy then to create a new generic class DataObjFactory<DataObjType>
as a replacement for Foo and Bar.
Upvotes: 2