gpt4 book ai didi

c# - 数据访问层的设计模式

转载 作者:可可西里 更新时间:2023-11-01 08:17:41 25 4
gpt4 key购买 nike

您可能会觉得这是作业,对此我很抱歉。我进行了搜索,但找不到合适的答案。

所以我的问题是:

我有几个类,每个类都有一个保存方法。所以我为数据库处理创建了一个单独的类。

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 类来实现所有的类并不合适。

我的问题:

  1. 什么设计模式适合解决这个问题?
  2. 将 DBConnection 创建为类是好的做法吗? (或者它应该是一个接口(interface))

我找到了几篇关于使用工厂方法的 DA 层的文章,但据我所知,这种模式不适合我的情况。

最佳答案

通常,如果我不能使用任何现有框架,我会同时使用 Repository 和 Active 模式。

为简单起见,您可以仅使用存储库模式。我通常这样定义它:

public interface IEntity<T> { }

// Define a generic repository interface
public interface IRepository<TKey, TEntity>
where TEntity : IEntity<TKey>
{
void Add(TEntity entity);
void AddRange(IEnumerable<TEntity> entities);
IEntity<TKey> Get(TKey key);
IEnumerable<TEntity> GetRange(IEnumerable<TKey> keys);
IEnumerable<TEntity> GetAll();
// ..., Update, Delete methods
}

// Create an abstract class that will encapsulate the generic code
public abstract class Repository<TKey, TEntity> : IRepository<TKey, TEntity>
where TEntity : IEntity<TKey>
{
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<TKey> 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 class 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
}
}

显然,在执行您自己的实现时,您必须考虑线程安全,充分利用事务,特别是跨不同的实体存储库。

//  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,因为它可能会变得极其复杂,特别是尝试开发最通用的解决方案。

关于c# - 数据访问层的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13748993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com