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

问题描述 投票:4回答:1

我曾经通过存储库,UnitOfWork和依赖项注入实现EF。

我现在正在尝试使用存储库,UnitOfWork和依赖注入来实现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?(这样做有意义吗?)

我曾经通过存储库,UnitOfWork和依赖注入实现EF。我现在正在尝试使用存储库,UnitOfWork和依赖项注入来实现ADO.NET。-但这会引起问题...

c# asp.net-mvc spring-mvc asp.net-mvc-4 model-view-controller
1个回答
0
投票
         /* 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);
© www.soinside.com 2019 - 2024. All rights reserved.