Mage
Mage

Reputation: 969

Linq query to get results from DB in ASP.NET MVC 2

How do I query using Ling to Entities.

I want to get back the total number of rows for a specific user.

I created a table with an ID(PK), Username, and PhoneNumber.

In my controller, I am able to do this and see my entities:

public ActionResult UserInfo()
        {
            using (UserInfoEntities db = new UserInfoEntities())
            {

            }
            return View();
        }

How do I query to return the total number of rows and declare it to a variable (totalrows) so that I can do thge following:

ViewData["TotalRows"] = totalrows

If there is a better way I am open to suggestions...

Thanks!!

Upvotes: 0

Views: 247

Answers (2)

James Hull
James Hull

Reputation: 3689

Yep Matthew is right. The count method does exactly what you need! Although, I would recommend looking at ViewModels to pass your data to your view (rather than ViewData) and some kind of DAL pattern, such as the repository pattern, for querying your entities.

Upvotes: 1

Matthew Abbott
Matthew Abbott

Reputation: 61617

Probably something like:

int count = db.SomeTable.Where(r => r.Username.Equals("username")).Count();

Upvotes: 2

Related Questions