Simpletest way to fetch database records in Razor

Hello friends,
Today we are discussing how to fetch data from database in Razor.
You can connect with database using method.
This will return you database object.
For example
Database dbCon = Database.Open(“MyBlog”);

Now to fetch records from database you have mainly three methods which are
1) dbCon.Query() :- This method return IEnumeration object. You can use this method. Or in the other words it will return no of record sets which are available after running the specific query.
2) dbCon.QuerySingle():- By the name it will return single record set or single object. You can use it when you are sure the query will return single result set.
3) dbCon.QueryValue() :-
  This method is like your scalar method in ADONET. It will return scalar value or single value.

Here I am taking example of fetching multiple rows from a table.
Suppose I have a tag table and I need to fetch records from database and display it in a tabular html format. Then below are the steps.
1) Create database object
Database dbCon = Database.Open("MyBlog");
2) Get IEnumerable object  by query
var TagListRecords = dbCon.Query("SELECT * FROM lkuTag");
3) Run for loop on IEnumerable object  and print the columns of table result set
@foreach (var tagrecord in TagListRecords) {

You will get following screen after running it.

I hope it is simplest way to fetch records.

In next topic we will discuss how to insert records in database in razor.

Till than thanks a lot.

Take care
Rajat Jaiswal


One thought on “Simpletest way to fetch database records in Razor

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s