如何使用实体框架合并结果并将结果绑定到gridview

时间:2013-02-02 06:24:53

标签: c# asp.net entity-framework

大家好我已经编写了以下查询来获取基于技术ID的信息,我正在得到正确的结果但是我不知道如何根据我的要求合并结果

循环将根据加载结果的网格进行处理,当有2行时,此循环将运行多次,然后我将在每个循环上得到结果,记录我想要绑定在一起结果网格,就像我们合并数据集一样,我想合并结果

foreach (GridViewRow row in grdForum.Rows)
{
int quesID = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
var lastpost = db.tblQuestions.Where(u => u.TechID.Equals(quesID)).OrderByDescending(u => u.DatePosted).Take(1).ToList();
grdnewUser.DataSource = lastpost.ToList();
grdnewUser.DataBind();
}

 public class Results
    {
        public DateTime DatePosted;
        public string QuestionTitle;
        public string UserName;
    }

public void bindLastPost()
{
   ArrayList a = new ArrayList();
   foreach (GridViewRow row in grdForum.Rows)
   {
    int quesID = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
    var lastpost = db.tblQuestions.Where(u => u.TechID.Equals(quesID)).OrderByDescending(u => u.DatePosted).Take(1).FirstOrDefault();

    a.Add(new Results { DatePosted = lastpost.DatePosted, QuestionTitle = lastpost.QuestionTitle, UserName = lastpost.UserName });
   }
      grdnewUser.DataSource = a;
      grdnewUser.DataBind();

根据user1974729回答

int[] quesID;
            int i = 0;
            foreach (GridViewRow row in grdForum.Rows)
            {
                quesID[i] = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
                i++;
            }
            //Check this part to find out how u will implement the Contains in Linq
            var lastpost = from e in db.tblQuestions where quesID.Contains(e.TechID) select e;

            }

1 个答案:

答案 0 :(得分:-1)

u r doing this inside the foreach loop//
No matter how many times u do this , only the last time u do it will stick..
grdnewUser.DataSource = lastpost.ToList(); //This is done only one time

所以我想你要找的是如何在Linq中实现CONTAINS ..

int[] quesID;
int i = 0;
foreach (GridViewRow row in grdForum.Rows)
{
 quesID[i] = Convert.ToInt16(grdForum.DataKeys[row.RowIndex].Values["TechID"].ToString());
 i++;
}

//Check this part to find out how u will implement the Contains in Linq
var lastpost = db.tblQuestions.Where(u => quesID.Contains(quesID)).OrderByDescending(u => u.DatePosted).Take(1).ToList();
grdnewUser.DataSource = lastpost.ToList();
grdnewUser.DataBind();
}