c# – 数据访问层的设计模式
发布时间:2020-12-15 04:10:32 所属栏目:百科 来源:网络整理
导读:你可能觉得这是家庭作业,因为我很抱歉.我搜索过但找不到正确答案. 所以我的问题是: 我有几个类,每个类都有一个方法来保存.所以我创建了一个单独的数据库处理类. namespace HospitalMgt.Data{ public static class DBConnection { public static string cons
你可能觉得这是家庭作业,因为我很抱歉.我搜索过但找不到正确答案.
所以我的问题是: 我有几个类,每个类都有一个方法来保存.所以我创建了一个单独的数据库处理类. namespace HospitalMgt.Data { public static class DBConnection { public static string constr = "Data Source=ABD;Initial Catalog=HospitalMgt;User Id=sa;Password=123"; public static SqlConnection con; // public static SqlCommand com; public static SqlConnection OpenConnection() { con= new SqlConnection(constr); con.Open(); return con; } } } 但是,我认为不适合使用DBConnection类来实现所有的类. 我的问题 : >什么设计模式适合克服这个问题? 我使用Factory方法发现了几篇有关DA层的文章,但是据我所知,这种模式并不适合我的情况. 解决方法
通常,如果我不能使用任何现有的框架,我同时使用Repository和Active模式.
为了简单起见,您只能使用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 } } 您现在有足够的工具来操作数据库,但如果需要,可以使用Active模式. 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(); } 只要确定你真的想创建自己的DAL,因为它可以结束蜂蜜的复杂,特别是试图开发最通用的解决方案. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |