ASP.NET - Enlazar clases que manejan base de datos asp.net

 
Vista:
Imágen de perfil de Reinaldo

Enlazar clases que manejan base de datos asp.net

Publicado por Reinaldo (3 intervenciones) el 30/04/2016 04:32:10
Cordial saludo.
Estoy tratando de enlazar unas clases que manejan una base de datos en ASP.NET pero me siguen apareciendo los siguientes errores:

1
2
3
4
The name ‘titleOfCourtesy’ does not exist in the current context.
The name ‘lastName’ does not exist in the current context.
The name ‘firstName’ does not exist in the current context.
The name ‘EmployeeID’ does not exist in the current context.
Las clases las tome de un libro, pero en este no describen cómo enlazarlas para que conecten a la página aspx. Aquí los códigos de las clases:

EmployeeDB.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web.Configuration;
using WebEmpleados2;
 
 
 
 
namespace WebEmpleados2
{
    class EmployeeDB
    {
        private string connectionString;
 
        public EmployeeDB()
        {
            // Get default connection string.
 
            connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        }
 
        public EmployeeDB(string connectionString)
        {
            // Set the specified connection string.
            this.connectionString = connectionString;
        }
 
        public int InsertEmployee(EmployeeDetails emp)
        {
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("InsertEmployee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10));
            cmd.Parameters["@FirstName"].Value = emp.FirstName;
            cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20));
            cmd.Parameters["@LastName"].Value = emp.LastName;
            cmd.Parameters.Add(new SqlParameter("@TitleOfCourtesy",
            SqlDbType.NVarChar, 25));
            cmd.Parameters["@TitleOfCourtesy"].Value = emp.TitleOfCourtesy;
            cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
            cmd.Parameters["@EmployeeID"].Direction = ParameterDirection.Output;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return (int)cmd.Parameters["@EmployeeID"].Value;
            }
            catch (SqlException err)
            {
                // Replace the error with something less specific.
                // You could also log the error now.
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
        }
 
        public void DeleteEmployee(int employeeID)
        {
 
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("DeleteEmployee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
            cmd.Parameters["@EmployeeID"].Value = employeeID;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException err)
            {
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
 
        }
 
        public void UpdateEmployee(EmployeeDetails emp)
        {
 
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("UpdateEmployee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 10));
            cmd.Parameters["@FirstName"].Value = firstName;
            cmd.Parameters.Add(new SqlParameter("@LastName", SqlDbType.NVarChar, 20));
            cmd.Parameters["@LastName"].Value = lastName;
            cmd.Parameters.Add(new SqlParameter("@TitleOfCourtesy", SqlDbType.NVarChar,
            25));
            cmd.Parameters["@TitleOfCourtesy"].Value = titleOfCourtesy;
            cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
            cmd.Parameters["@EmployeeID"].Value = EmployeeID;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException err)
            {
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
 
        }
 
        public EmployeeDetails GetEmployee(int employeeID)
        {
 
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("GetEmployee", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@EmployeeID", SqlDbType.Int, 4));
            cmd.Parameters["@EmployeeID"].Value = employeeID;
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                // Check if the query returned a record.
                if (!reader.HasRows) return null;
                // Get the first row.
                reader.Read();
                EmployeeDetails emp = new EmployeeDetails(
                (int)reader["EmployeeID"], (string)reader["FirstName"],
                (string)reader["LastName"], (string)reader["TitleOfCourtesy"]);
                reader.Close();
                return emp;
            }
            catch (SqlException err)
            {
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
 
        }
 
        public List<EmployeeDetails> GetEmployees()
        {
 
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("GetAllEmployees", con);
            cmd.CommandType = CommandType.StoredProcedure;
            // Create a collection for all the employee records.
            List<EmployeeDetails> employees = new List<EmployeeDetails>();
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
 
                    EmployeeDetails emp = new EmployeeDetails(
                    (int)reader["EmployeeID"], (string)reader["FirstName"],
                    (string)reader["LastName"], (string)reader["TitleOfCourtesy"]);
                    employees.Add(emp);
                }
                reader.Close();
                return employees;
            }
            catch (SqlException err)
            {
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
 
 
        }
 
        public int CountEmployees()
        {
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("CountEmployees", con);
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                con.Open();
                return (int)cmd.ExecuteScalar();
            }
            catch (SqlException err)
            {
                throw new ApplicationException("Data error.");
            }
            finally
            {
                con.Close();
            }
        }
    }
}

EmployeeDetails.cs:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
 
namespace WebEmpleados2
{
    public class EmployeeDetails
    {
        private int employeeID;
        public int EmployeeID
        {
            get { return employeeID; }
            set { employeeID = value; }
        }
        private string firstName;
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }
        private string lastName;
        public string LastName
        {
            get { return lastName; }
            set { lastName = value; }
        }
        private string titleOfCourtesy;
        public string TitleOfCourtesy
        {
            get { return titleOfCourtesy; }
            set { titleOfCourtesy = value; }
        }
        public EmployeeDetails(int employeeID, string firstName, string lastName,
        string titleOfCourtesy)
        {
            EmployeeID = employeeID;
            FirstName = firstName;
            LastName = lastName;
            TitleOfCourtesy = titleOfCourtesy;
        }
    }
}
 
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebEmpleados2;
using System.Text;
 
namespace WebEmpleados2
{
    public partial class Default : System.Web.UI.Page
    {
        // Create the database component so it's available anywhere on the page.
        private EmployeeDB db = new EmployeeDB();
 
        protected void Page_Load(object sender, EventArgs e)
        {
            WriteEmployeesList();
            // The ID value is simply set to 0, because it's generated by the
            // database server and filled in automatically when you call
            // InsertEmployee().
            int empID = db.InsertEmployee(
            new EmployeeDetails(0, "Mr.", "Bellinaso", "Marco"));
            Label1.Text += "<br />Inserted 1 employee.<br />";
            WriteEmployeesList();
            db.DeleteEmployee(empID);
            Label1.Text += "<br />Deleted 1 employee.<br />";
            WriteEmployeesList();
        }
        private void WriteEmployeesList()
        {
            StringBuilder htmlStr = new StringBuilder("");
            int numEmployees = db.CountEmployees();
            htmlStr.Append("<br />Total employees: <b>");
            htmlStr.Append(numEmployees.ToString());
            htmlStr.Append("</b><br /><br />");
            List<EmployeeDetails> employees = db.GetEmployees();
            foreach (EmployeeDetails emp in employees)
            {
                htmlStr.Append("<li>");
                htmlStr.Append(emp.EmployeeID);
                htmlStr.Append(" ");
                htmlStr.Append(emp.TitleOfCourtesy);
                htmlStr.Append(" <b>");
                htmlStr.Append(emp.FirstName);
                htmlStr.Append("</b>, ");
                htmlStr.Append(emp.LastName);
                htmlStr.Append("</li>");
            }
            htmlStr.Append("<br />");
            Label1.Text += htmlStr.ToString();
        }
    }
}

Espero me puedan ayudar. Gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Enlazar clases que manejan base de datos asp.net

Publicado por khristian (83 intervenciones) el 12/05/2016 20:52:10
Tienes que instanciar la clase.
Solo podrás acceder a los metodos públicos..
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

Enlazar clases que manejan base de datos asp.net

Publicado por Juan Carlos Ramirez (2 intervenciones) el 19/05/2016 23:30:01
Debes de importar las referencias de las clases.. para que de esta manera las reconosca.. y no te marque que no existen..
lo puedes hacer desde las referencias que aparecen en tu proyecto.. clic derecho agreagar referencia y en solucion ahi deveran pareer la ruta de donde estan tus clases la seleccionas y listo..
las puedes importar en el from.. pones using y la direccion que te parecio en las referncias. la que aparece cuando la agregas
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Enlazar clases que manejan base de datos asp.net

Publicado por Esmeralda (19 intervenciones) el 20/05/2016 15:54:37
Puedes crear un objeto de tu entidad para poder un utilizar todos sus atributos por medio de los metodos get y set.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar