如何使用Generic Repository实现ADO.NET?

时间:2017-03-03 11:13:45

标签: c# asp.net-mvc spring-mvc asp.net-mvc-4 model-view-controller

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

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

这是我的Repository界面:

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? (这样做有意义吗?)

1 个答案:

答案 0 :(得分: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);