आम तौर पर, अगर मैं किसी भी मौजूदा ढांचे का उपयोग नहीं कर सकते हैं, मैं दोनों भंडार और सक्रिय पैटर्न का उपयोग करें:
यहाँ इसके बारे में एक अच्छा लेख है।
सादगी के लिए, आप केवल रिपोजिटरी पैटर्न का उपयोग कर सकते हैं। मैं सामान्य रूप से इस तरह इसे परिभाषित:
// 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
}
}
}
जाहिर है, जब अपने स्वयं के कार्यान्वयन कर रही है, तो आप खाते धागा सुरक्षा में लेन-देन की का उपयोग कर अच्छा कर रही है, विशेष रूप से विभिन्न इकाई खजाने भर में रखना चाहिए।
// 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();
}
बस सुनिश्चित करें कि आप वास्तव में के बाद से यह extremelly जटिल beeing समाप्त कर सकते हैं अपनी खुद की दाल बनाना चाहते हो, विशेष रूप से सबसे सामान्य समाधान विकसित करने की कोशिश।
रिपोजिटरी पैटर्न पर एक नज़र डालें, ऐसा लगता है जैसे यह आपकी मदद कर सकता है। – BenjaminPaul
यदि आपके कोड में उपयोगकर्ता आईडी और पासवर्ड असली हैं, तो आपको उन्हें तुरंत छिपाना चाहिए। –
क्या आप सिंगलटन बनाने की कोशिश कर रहे हैं? यदि हां, तो आप इसे गलत कर रहे हैं। –