Timpe
Timpe

Reputation: 1

Method return data type when using LINQ to Entities

I have database table Staff having the columns Name, Email, Address and DateOfBirth. In my web application I have a separate class ClassMyBase having a couple of methods. One of the methods uses LINQ to Entities:

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

... and then in ButtonShowAll event handler in WebForm1:

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

So far so good, BUT if I add filtering to my 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
            }
      }
}

my method won’t work because the return data type is no more same as previously. Any easy solutions? What could this return data type xyz be?

If I put everything together (no separate class in my project) and have only ButtonShowAll it will work all right, so like this:

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();
}

Upvotes: 0

Views: 87

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156938

This part of your code creates an anonymous class:

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

You should name it explicitly, then that class name will be used, and you can type your return type:

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

Additionally, you might want to use ToList(), or change your return type to IEnumerable<Staff>, since the LINQ query will not return a List<Staff>:

var selectedRows = ...
                   .ToList();

Upvotes: 1

Related Questions