使用 LINQ to 实体时的方法返回数据类型

本文关键字:方法 返回 数据类型 LINQ to 实体 使用 | 更新日期: 2023-09-27 18:33:41

我有数据库表Staff具有NameEmailAddressDateOfBirth列。在我的 Web 应用程序中,我有一个单独的类ClassMyBase有几个方法。其中一种方法使用 LINQ to Entities:

public static List<Staff> ShowAll()
{
     using (ModelPersonnelContainer myContainer = new 
            ModelPersonnelContainer())
     {
         return myContainer.Staff.ToList();
     }
}

。然后在WebForm1 ButtonShowAll事件处理程序中:

protected void ButtonShowAll_Click(object sender, EventArgs e)
{
      GridViewAll.DataSource = ClassMyBase.ShowAll();
      GridViewAll.DataBind();
}

到目前为止一切顺利,但是如果我在我的public static List<Staff> ShowAll()中添加过滤:

public static xyz ShowAll()
{
      using (ModelPersonnelContainer myContainer = new 
                ModelPersonnelContainer())
      {
            selectedRrows=from item in myContainer.Staff
                select new
            {
              Name=item.Name,
              Email=item.Email
            }
      }
}

我的方法不起作用,因为返回数据类型与以前不同。有什么简单的解决方案吗?这种返回数据类型xyz可能是什么?

如果我将所有内容放在一起(我的项目中没有单独的类)并且只有ButtonShowAll它就可以正常工作,就像这样:

protected void ButtonShowAll_Click(object sender, EventArgs e)
{
            using (ModelPersonnelContainer myContainer = new 
            ModelPersonnelContainer())
            {
                var selectedRows = from item in myContainer.Staff
                                  select new
                                  {
                                    Name=item.Name,
                                    Email=item.Email
                                  };
                GridView1.DataSource = selectedRows.ToList();
                GridView1.DataBind();
}

使用 LINQ to 实体时的方法返回数据类型

代码的这一部分创建一个匿名类:

new
{
    Name=item.Name,
    Email=item.Email
}

您应该显式命名它,然后将使用该类名,并且可以键入返回类型:

new Staff()
{
    Name=item.Name,
    Email=item.Email
}

此外,您可能希望使用 ToList() 或将返回类型更改为 IEnumerable<Staff> ,因为 LINQ 查询不会返回List<Staff>

var selectedRows = ...
                   .ToList();