Accessing C # Generic Inheritance Data

Hi, I want to create a base class for inheritance, but I am having some problems.

I have two classes that do almost identical work, but get the data they work with from different databases and use different internal data structures to manage the data. I want to have a virtual doSomething method in the base and perfectly virtual dataAccess method in the database.

The second problem can be solved using generics, but I can not use generics to solve the first problem, since the DBMl context constructor used is not without parameters.

I'm all wrong about that. I try to be dry, but it seems to work against inheritance.

Sample 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 } } 
+4
source share
2 answers

Foo and Bar should not call the database constructor themselves, the database object should be a constructor parameter (instead of the connection string). This principle is called Dependency Injection and will solve most of your problems. It should be easy to create a new generic DataObjFactory<DataObjType> class as a replacement for Foo and Bar.

+2
source

You have to make a base class that encapsulates the functionality you want to share. In this case, you can reuse the data access code if you use the interface on the object of the object. Something like that:

 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); } } 

You can then 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); } } 
0
source

All Articles