Home > Software design >  what is IEnumerable do
what is IEnumerable do

Time:07-24

ASP.NET MVC: I fail to understand the following code:

public IEnumerable<Role> GetRoles()     // what does this line do?
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))
    {
        // and what does this line do?
        return con.Query<Role>("Usp_GetRoles", null, null, true, 0, CommandType.StoredProcedure).ToList();        
    }
}

CodePudding user response:

In simple term, IEnumerable interface is a generic interface which allows looping over generic or non-generic lists.

As you are using dapper and dapper Query only guarantees to hand you an IEnumerable<T>. we can convert it to a list as soon as we want to return a result.

// GetRoles Method with return type IEnumerable of Role Since the below Query Extension method returns IEnumerable<T>
public IEnumerable<Role> GetRoles()         
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))
        {
            //calling Query Extension method with passing arguments which includes stored procedure name, set of parameters and command type
            return con.Query<Role>("Usp_GetRoles", null, null, true, 0, CommandType.StoredProcedure).ToList();       
        }
    }
  • Related