Mega Code Archive

 
Categories / ASP.Net Tutorial / ADO Net Database
 

Building a Data Access Layer with a User-Defined Type

File: App_Code\DBDataLayer.cs using System; using System.Data; using System.Data.SqlClient; using System.Web.Configuration; using System.Collections.Generic; public class DBDataLayer {     private static readonly string _connectionString;     public List<DBProduct> GetAll()     {         List<DBProduct> results = new List<DBProduct>();         SqlConnection con = new SqlConnection(_connectionString);         SqlCommand cmd = new SqlCommand("SELECT Product FROM DBProducts", con);         using (con)         {             con.Open();             SqlDataReader reader = cmd.ExecuteReader();             while (reader.Read())             {                 DBProduct newProduct = (DBProduct)reader["Product"];                 results.Add(newProduct);             }         }         return results;     }     public void Insert(DBProduct productToAdd)     {         SqlConnection con = new SqlConnection(_connectionString);         SqlCommand cmd = new SqlCommand("INSERT DBProducts (Product) VALUES (@Product)", con);         cmd.Parameters.Add("@Product", SqlDbType.Udt);         cmd.Parameters["@Product"].UdtTypeName = "DBProduct";         cmd.Parameters["@Product"].Value = productToAdd;         using (con)         {             con.Open();             cmd.ExecuteNonQuery();         }     }         static DBDataLayer()     {         _connectionString = WebConfigurationManager.ConnectionStrings["Products"].ConnectionString;     } } File: ShowDBDataLayer.aspx <%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">     <title>Show DBDataLayer</title> </head> <body>     <form id="form1" runat="server">     <div>     <asp:GridView         id="grdProducts"         DataSourceID="srcProducts"         Runat="server" />     <br />     <fieldset>     <legend>Add Product</legend>     <asp:DetailsView         id="dtlProduct"         DataSourceID="srcProducts"         DefaultMode="Insert"         AutoGenerateInsertButton="true"         AutoGenerateRows="false"         Runat="server">         <Fields>         <asp:BoundField DataField="Title" HeaderText="Title" />         <asp:BoundField DataField="Director" HeaderText="Director" />         <asp:BoundField DataField="Totals"            HeaderText="Box Office Totals" />         </Fields>     </asp:DetailsView>     </fieldset>     <asp:ObjectDataSource         id="srcProducts"         TypeName="DBDataLayer"         DataObjectTypeName="DBProduct"         SelectMethod="GetAll"         InsertMethod="Insert"         Runat="server" />     </div>     </form> </body> </html>