Dev
Dev

Reputation: 137

How to retrieve one record from SQL Server database in MVC Model

I am working on Visual C# MVC project. I am using databse first approach in my model.My project is about developing an appmarket where users can buy apps. I used partial view in home page which will conatin details of different apps in different partial views.Like App1 in 1st partial view, App2 in 2nd partial view, so on. For this I used foreach loop.

In each partial view there is link called MoreInfo, so when user clicks on that they will go inside MoreInfo page. In database I have fields such as app info, app cost, description etc which will be displayed inside MoreInfo page. All these fields are in one table called Apps table.

My problem here is if i use forach loop inside MoreInfo page, then I am getting information of each record from database. To be more clear, in Database I have two records for Description field called "Description 1" and "Description 2". If i use foreach loop, then it is displaying two views, one for Description 1 and another for description 2 in same page. What I want is Desription of 1st app in first MoreInfo page and second description in 2nd MoreInfo view and so on.
can someone help me in this? Thanks..

Upvotes: 1

Views: 2396

Answers (3)

JSHunjan
JSHunjan

Reputation: 397

You should be using Linq to get one record as per your condition. try something like this (this is only code to show you the logic as we are not sure what variables you have used).

var result=(from x in dbContext.TableName where column==variable select x).FirstOrDefault()

I hope it will help.

Upvotes: 0

Botonomous
Botonomous

Reputation: 1764

Assuming you are using Entity Framework: Enumerable.FirstOrDefault will do this for you. You can load it into the TSource type.

Here is a link: http://msdn.microsoft.com/en-us/library/bb340482.aspx

var someobj = db.someEnumerable.FirstOrDefault(x => // Condition);

Upvotes: 1

evanmcdonnal
evanmcdonnal

Reputation: 48096

If you're using LINQ to SQL or EF you can tack FirstOrDefault() onto your call which will return the first value or in most cases null (default value for reference types). If you're using something like SQLConnection or invoking a sproc just change your SELECT ... FROM to SELECT TOP 1 .... FROM

Upvotes: 1

Related Questions