Retrieving and Displaying a specific record with EF
We can use Language INtegrated Query (LINQ) in Entity Framework to query our database and find a selected entry. This will be
useful for finding and displaying a specific blog entry.
In the last task, we redirected the user to a page, and placed the Id of the Blog Entry in the URL in the following format ViewBlogEntry.aspx?Id=1. The "?Id=1" portion of the URL is known as a query string, and allows us to pass parameters between pages. (It should be noted that these can be both seen and modified by the end user - this can have security implications depending on the nature of the web application)
We will use that Id's value and use it to retrieve the relevant blog entry.
Add a new web form called ViewBlogEntry.aspx and add three literal controls to the page. Name them litTitle, litDate and litBody. Place them inside
p tags respectively.
Switch to the code behind (ViewBlogEntry.aspx.cs) page, and add the following code inside the Page_Load method:
string entryIdString = Request.QueryString["Id"];
int entryId = int.Parse(entryIdString);
These two lines of code retrieve the value of the query string, which is initially in string format - our Id is a numeric value, so the next line parses the value into integer format
Create a new instance of our Database Entities with the following line of code:
Database Entities db = new DatabaseEntities();
The next line of code we add will use something called Method Syntax to query for a single value from the database using the Id of the object:
var entry = db.BlogEntries.Single(p => p.Id == entryId);
The p is used as a parameter to identify what we are querying, in this case a blog entry, where the BlogEntry's Id matches the entryId we got from the querystring
Finally set the various literals to display the title, date and body of our blog entry - the first line of code to do that is shown below, you will need to add an additional
litTitle.text = entry.Title;