当我的返回类型是IEnumerable时,如何获取var输出数据

时间:2017-12-03 17:08:27

标签: c# sql-server

我需要从var result = new获取数据,而不是从IEnumerable获取数据。请帮助我,如果他们有任何替代解决方案,请告诉我。

public IEnumerable<Employee_Join> GetEmployees(int paginate)    
{
    int FilterdCount = 0;

    using (SqlConnection con = Db.Dbcontect)
    {
        var employee = new List<Employee_Join>();

        con.Open();

        SqlCommand cmd = new SqlCommand("SP_GetEmployees_By_Pagination", con);
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Pagination", paginate);
        cmd.Parameters.AddWithValue("@Total", 5);

        SqlDataReader rdr = cmd.ExecuteReader();

        if (rdr.HasRows == true)
        {
            while (rdr.Read())
            {
                Employee_Join emp = new Employee_Join();

                if (!Convert.IsDBNull(rdr["EmployeeId"]))
                {
                    emp.Emp_Id = Convert.ToInt32(rdr["EmployeeId"]);
                }

                emp.EmpName = rdr["EmpName"].ToString();
                emp.Email = rdr["Email"].ToString();
                emp.Cnt_Name = rdr["CountryName"].ToString();

                employee.Add(emp);
            }
        }

        var result = new
                    {
                        iTotalRecords = GetTotalEmployeeCount(),
                        iTotalDisplayRecords = FilterdCount,
                        aaData = employee
                    };

        return employee;
    }
}

我需要var result = new输出而不是员工

1 个答案:

答案 0 :(得分:1)

如果你想返回result,你需要从中创建一个ViewModel / DTO类,因为C#不允许你从方法中返回匿名对象(技术上你可以,但这会产生很多额外的工作)在路上,所以请不要。)

public class MyCustomDTO
{
    public Type iTotalRecords { get; set; }
    public Type iTotalDisplayRecords { get; set; }
    public Type employee { get; set; }
}

更改代码,使其不会创建一个匿名类型,而是创建新类:

var result = new MyCustomDTO
{
    iTotalRecords = GetTotalEmployeeCount(),
    iTotalDisplayRecords = FilterdCount,
    aaData = employee
};

return employee;

最后更改为函数的返回类型以反映正确的类型

public MyCustomDTO GetEmployees(int paginate)   { /* ... */}