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

房东的猫 提交于 2020-01-06 05:26:16

问题


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!!


回答1:


Probably something like:

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



回答2:


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.



来源:https://stackoverflow.com/questions/3379080/linq-query-to-get-results-from-db-in-asp-net-mvc-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!