简体   繁体   中英

How to implement ADO.NET with Generic Repository?

I have once implemented EF with Repository, UnitOfWork and Dependency Injection.

Iám now trying to implement ADO.NET with Repository, UnitOfWork and Dependency Injection.- But it causes problems

Here is my Repository interface:

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

Here Repository implementation:

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")),
                }
            }
        }
    }
}

Is there a way to Create a "Generic Repository" for ADO.NET (how to implement it `?)?

Here is Controller:

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);
    }
}

How to make Unitofwok when using ADO.NET? (Does it make sense to do it?)

         /* 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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