如何使用EF / LINQ在asp.net中显示多条记录(最佳方法)

时间:2013-07-08 09:32:18

标签: asp.net

我看到很多人以某种方式显示数据记录,我认为个人效率不高,我遵循这些方法但不满意,因为我认为在应用程序生命周期的某些时候,数据记录可能达不到大量的,这样,循环遍历所有记录,生成数据,然后将数据打印到浏览器将减慢应用程序执行和性能,例如看看这段代码,

var query2 = from m in JE.J_Posted_Jobs_Tbl
join n in JE.J_Genders_Tbl on m.J_Job_Location equals n.J_Gender_ID
select new { 
m.J_Job_ID,
m.J_Job_Title,
m.J_Job_Description,
m.J_Job_Package,
m.J_Job_Timing,
n.J_Gender
};


string datarow = "";  
foreach(var result in query2 ){
datarow = datarow + "<div class='eachjob'>"+
        "<a href='Employeer-Details.aspx'>"+
        "<div class='eachjobCompanyImg'>"+
"<img src='includes/images/premiummembers/premiummeber1.gif' width='60' height='60'/>"+
"</div>"+"</a>"+"<div class='eachjobName'>
<a href='Jobs-Details.aspx?J_PostedJob_ID="+result.J_Job_ID+"'>"+result.J_Job_Title+"
</a>
     </div>"+"<div class='eachjobName'>Islamabad</div>"+
            "<div class='eachjobDescription'>"+
                ""+result.J_Job_Description+""+
        "</div>"+
        "<div class='eachjobName'>"+result.J_Job_Package+"</div>"+
        "<div class='eachjobName'>"+result.J_Job_Timing+"</div>"+
        "<div class='eachjobName'>"+result.J_Gender+"</div>"+
        "<div class='eachjobFuncDiv'>"+
            "<div class='eachjobFunDivBlock'>"+
                "<div class='eachjobFunDivBlockImg'>"+
                    "<img src='includes/images/jobFunLogos/jobMarkHired.png' />"+
                "</div>"+
                "<div class='eachjobFunDivBlockName'>Mark Hired</div>"+
            "</div>"+
             "<div class='eachjobFunDivBlock'>"+
                "<div class='eachjobFunDivBlockImg'>"+
                    "<img src='includes/images/jobFunLogos/jobMakeDisApply.png' />"+
                "</div>"+
                "<div class='eachjobFunDivBlockName'>Disable Job</div>"+
            "</div>"+
        "</div></div>";
}
YourPostedJobs.InnerHtml = datarow;

is this method any efficient? If not, plz tell me an efficient way which is 
application friendly.
Thanks in advance!

1 个答案:

答案 0 :(得分:2)

一个显而易见的改进是一次返回一页数据,而不是一次性返回每个项目。为此,您可以在查询中使用Linq Skip()Take()

var query2 = from m in JE.J_Posted_Jobs_Tbl
join n in JE.J_Genders_Tbl on m.J_Job_Location equals n.J_Gender_ID

select new { 
m.J_Job_ID,
m.J_Job_Title,
m.J_Job_Description,
m.J_Job_Package,
m.J_Job_Timing,
n.J_Gender
};

var pagedQuery = q2.Skip(pageSize * (page -1)).Take(pageSize);

另一个步骤是通过连接类似的字符串来停止构建HTML。当然最好返回数据并让浏览器使用javascript渲染它!或者如果必须在服务器上构建它,至少要使用StringBuilderstring.Format()