Search code examples
mysqlsqlasp.net-mvc-3enterprise-library

Execute stored procedure in mvc through EnterpriseLibrary


I am tyring to develop a sample project in mvc. In this, i tried to get the userlist from database (mysql). i am using enterprise library dll to set the database connectivity.

 public IEnumerable<UserViewModel> GetUserList()
    {
        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database db = factory.Create("MySqlConnection");
        DbCommand dbc = db.GetStoredProcCommand("uspGetUserList");
        dbc.CommandType = CommandType.StoredProcedure;

        return db.ExecuteDataSet(dbc);
    }

i know the executedataset is to execute only dataset type... i want the command that execute IEnumerable type..... thank you


Solution

  • If you want to return an IEnumerable type without manually constructing it (either from a DataSet or an IDataReader) then you can use accessors.

    In your case your could would look like this:

    public IEnumerable<UserViewModel> GetUserList()
    {
        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database db = factory.Create("MySqlConnection");
        IEnumerable<UserViewModel> results = db.ExecuteSprocAccessor<UserViewModel>("uspGetUserList");
    
        return results;
    }
    

    This assumes that the UserViewModel can be mapped from the stored procedure result set (e.g. column names are the same name as the property names). If not, then you would need to create a custom mapper. See Retrieving Data as Objects from the Developer's Guide for more information about accessors.