通常情況下,如果我不能使用任何現有的框架,我同時使用存儲庫和主動模式。
爲了簡單起見,您只能使用Repository模式。我通常這樣定義它:
// Define a generic repository interface
public interface IRepository<Key, E> where E:IEntity<Key>>{
void Add(E entity);
void AddRange(IEnumerable<E> entities);
IEntity<Key> Get(Key key);
IEnumerable<E> GetRange(IEnumerable<Key> keys);
IEnumerable<E> GetAll();
// ..., Update, Delete methods
}
// Create an abstract class that will encapsulate the generic code
public abstract class Repository<K, E> where E:IEntity<K>>:IRepository<K, E>{
protected Repository(/*parameter you may need to implement the generic methods, like a ConnectionFactory, table name, entity type for casts, etc */){}
public override void Insert(IEntity<Key> entity){
// do the insert, treat exceptions accordingly and encapsulate them in your own and more concise Exceptions, etc
}
// ...
}
// Create the entities classes, one for each table, that will represent a row of that table
public class Car: IEntity<String>{/* Properties */}
// Create a specific repository for each table
// If the table have a composed key, just create a class representing it
public CarRepository: Repository<String, Car>{
public CarRepository(){/* pass the base parameters */}
// offer here your specific operations to this table entity
public IEnumerable<Car> GetByOwner(PersonKey ownerKey){
// do stuff
}
}
您現在有足夠的工具來操縱數據庫,但是如果需要,您可以使用活動模式。 一個簡單的例子:
public class Person:IEntity<PersonKey>{
public PersonKey Key{get;}
public IEnumerable<Car> OwnedCars{
get{
CarRepository rep = DBSingletons.Cars;
return rep.GetByOwner(this.Key);
}
set{
// do stuff
}
}
}
顯然,做你自己的實現時,你必須考慮到線程安全取得良好的使用事務處理的,特別是跨diferent實體庫。
// simple example
ITransaction t = TransactionFactory.GetNewTransaction();
t.begin();
try{
// create person entity
personRepository.Add(person, t);
// create cars assigned to person
carRepository.AddRange(cars, t);
t.commit();
}catch(Exception){
t.rollback();
}
只要確保你真的想創建自己的DAL,因爲它可以結束extremelly複雜beeing,特別是努力開發最通用的解決方案。
看看存儲庫模式,它聽起來像它可能會幫助你。 – BenjaminPaul
如果您的代碼中的用戶名和密碼是真實的,您應該立即隱藏它們。 –
你想創建一個Singleton嗎?如果是這樣,你做錯了。 –