With Razor, you can easily display data from a database in your web pages. You can create a database using programming code, but it is more typical (and easier) to use a design tool. An example of the Razor code for a simple table is as follows:
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 |
@{ var db = Database.Open("SmallBakery"); var selectQueryString = "SELECT * FROM Product ORDER BY Name"; } <html> <body> <h1>Small Bakery Products</h1> <table> <tr> <th>Id</th> <th>Product</th> <th>Description</th> <th>Price</th> </tr> @foreach(var row in db.Query(selectQueryString)) { <tr> <td>@row.Id</td> <td>@row.Name</td> <td>@row.Description</td> <td aligh="right">@row.Price</td> </tr> } </table> </body> </html> |
The output of this code would be a simple table listing all the products, their descriptions and respective prices. A designing tool available for database creation is SQL Server Compact Database design tool which is included in the WebMatrix. To develop simple database named MyDatabase using this tool, you need to follow these instructions:
Create a new web site and call the site “MyDatabase”. Create a new database which would be done using the WebMatrix. The name of this database would be MyDatabase.sdf. Now create a new table in the database by opening the MyDatabase.sdf and clicking New Table. The table designer would be opened by the WebMatrix. Having done this, create a new column named ‘ID’ and set the ‘Is Identity’ and ‘Is Primary Key’ to true. Is Primary Key tells the database that this will be the table’s primary key. Is Identity tells the database to automatically create an ID number for every new record and to assign it the next sequential number (starting at 1).
Similarly, create columns for Name, Description and Price. Having done that, save the table and name it ‘Product.’ After that, adding data to the table is a trivial task. With this simple method, users can create their personal database to handle the transactions and other requirements in a limited time.