繁体   English   中英

如何使用通用存储库实现 ADO.NET?

[英]How to implement ADO.NET with Generic Repository?

我曾经用 Repository、UnitOfWork 和 Dependency Injection 实现了 EF。

我现在正在尝试使用 Repository、UnitOfWork 和 Dependency Injection 来实现 ADO.NET。- 但它会导致问题

这是我的存储库界面:

public interface IUsersRepository
    {
        public User GetUser(int id);
    }

这里存储库实现:

public class UsersRepository: IUsersRepository
{
    private readonly string _connectionString;
    public UsersRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public User GetUser(int id)
    {
        // Here you are free to do whatever data access code you like
        // You can invoke direct SQL queries, stored procedures, whatever 

        using (var conn = new SqlConnection(_connectionString))
        using (var cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandText = "SELECT id, name FROM users WHERE id = @id";
            cmd.Parameters.AddWithValue("@id", id);
            using (var reader = cmd.ExecuteReader())
            {
                if (!reader.Read())
                {
                    return null;
                }
                return new User
                {
                    Id = reader.GetInt32(reader.GetOrdinal("id")),
                    Name = reader.GetString(reader.GetOrdinal("name")),
                }
            }
        }
    }
}

有没有办法为 ADO.NET 创建“通用存储库”(如何实现它`?)?

这是控制器:

public class UsersController: Controller
{
    private readonly IUsersRepository _repository;
    public UsersController(IUsersRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index(int id)
    {
        var model = _repository.GetUser(id);
        return View(model);
    }
}

使用 ADO.NET 时如何制作 Unitofwok? (这样做有意义吗?)

         /* controller */
               public class mycontroller:BaseController
                    {  
                       private readonly IRepo repo;

                       public mycontroller(IRepo _repo)
                       {
                         _repo=repo;
                       }
                       [httpGet]
                       public IActionResult<string> GetLastRecord()
                       {
                         return _repo.GetLastRecord();
                       }
                    }
        /* repo */    
                   public class repo
                       {
                          private readonly IDBContextFactory dBContextFactory; 
                          public repo(IDBContextFactory _dbContextFactory) 
                          {
                               _dbContextFactory=dBContextFactory;
                          }
                          public string GetLastRecord()
                          {  
  List< Student > studentDetails = new List<Student>();  
    studentDetails = ConvertDataTable<Student>(_dbCtextFactory.Select("mydb","select * from StudentDetail");
        /*refrence from this post https://stackoverflow.com/questions/33515552/converting-datatable-to-listentity-projectdracula */;

                          }
                       }

        /* interface of repo */
                       public interface IRepo
                       { 
                          public string GetLastRecord();
                       }

        /* some factory pattern for db context (multiple dbs) */
                       public class DBContextFactory
                       {
                           private SqlCommand BuildFactory(string dbName)
                           { 
                                switch(dbName)
                                {
                                    case 'mydb':
                                      return CreateMyDB();
                                }
                           }
                           private SqlCommand CreateMyDB()
                           { 
                              string connectionString = "your connection string";
                              SqlConnection connection =
                                new SqlConnection(connectionString));

                                SqlCommand command = new SqlCommand(connection);
                                return command.Open();

                           }
                           //Private SqlCommand GetMyOpenCommand()
                           public DataTable Select(string dbName,string query)
                           {


                                   SqlDataAdapter dataAdapter=new SqlDataAdapter();
                                   dataAdapter.SelectCommand=BuildFactory(dbName);
                                  DataTable dt =new DataTable();
                                   dataAdapter.Fill(dt);
                                   con.Close();
                                   return dt;
                           }

                       }
        /* factory in dependncy pattern */
                  public inteface IDBContextFactory
                  { 
                     SqlCommand BuildFactory(string dbName);
                     SqlCommand CreateMyDB();
                     DataTable Select(string dbName,string query)
                }
        /****** HERE IS YOUR GENERIC FILE ******/
        private static List<T> ConvertDataTable<T>(DataTable dt)  
        {  
            List<T> data = new List<T>();  
            foreach (DataRow row in dt.Rows)  
            {  
                T item = GetItem<T>(row);  
                data.Add(item);  
            }  
            return data;  
        }

        private static T GetItem<T>(DataRow dr)  
        {  
            Type temp = typeof(T);  
            T obj = Activator.CreateInstance<T>();  

            foreach (DataColumn column in dr.Table.Columns)  
            {  
                foreach (PropertyInfo pro in temp.GetProperties())  
                {  
                    if (pro.Name == column.ColumnName)  
                        pro.SetValue(obj, dr[column.ColumnName], null);  
                    else  
                        continue;  
                }  
            }  
            return obj;  
        } 
        /***** END OF GENERIC PART *****/
    /* USAGE OF GENERIC */
    List< Student > studentDetails = new List<Student>();  
    studentDetails = ConvertDataTable<Student>(dt);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM