0

J'utilise l'application principale asp.net avec le framework abp (Asp.net BoilerPlate). Je veux utiliser la procédure stockée pour obtenir les données et également pour implémenter des opérations CRUD dans cette première architecture de code. Quelle sera la meilleure façon de le faire?Comment utiliser la procédure stockée dans le noyau asp.net avec une architecture standard?

Merci à l'avance

+0

Avez-vous vu cet article: https://www.codeproject.com/Articles/1199648/Using-Stored- Procédure-User-Defined-Function-and-V – hikalkan

+0

@VishalG Est-ce résolu? – aaron

+0

@VishalG Est-ce résolu? – aaron

Répondre

2

Voici un exemple qui envoie un paramètre à une procédure stockée pour supprimer un utilisateur:

public async Task DeleteUser(EntityDto input) 
{ 
    await Context.Database.ExecuteSqlCommandAsync(
     "EXEC DeleteUserById @id", 
     default(CancellationToken), 
     new SqlParameter("id", input.Id) 
    ); 
}

Voir: Using Stored Procedure, User Defined Function and Views in a Custom Repository with ASP.NET Boilerplate

Le code source est publié sur Github: https://github.com/aspnetboilerplate/aspnetboilerplate-samples/tree/master/StoredProcedureDemo

0

Créez votre référentiel personnalisé pour pouvoir accéder à l'objet dbcontext et exécuter la requête sql en utilisant ce contexte. J'ai créé des méthodes d'aide dans mon référentiel personnalisé, l'espoir peut vous aider:

/// <summary> 
/// Map data from datareader to list object 
/// </summary> 
private List<T> MapToList<T>(DbDataReader reader) 
     { 
      var result = new List<T>(); 
      if (reader.HasRows) 
      { 
       var props = typeof(T).GetRuntimeProperties(); 
       var colMapping = reader.GetColumnSchema().Where(x => props.Any(p => p.Name.Equals(x.ColumnName, StringComparison.OrdinalIgnoreCase))).ToDictionary(key => key.ColumnName.ToLower()); 

       while (reader.Read()) 
       { 
        var item = Activator.CreateInstance<T>(); 
        foreach (var prop in props) 
        { 
         var propValue = reader.GetValue(colMapping[prop.Name.ToLower()].ColumnOrdinal.Value); 
         prop.SetValue(item, propValue == DBNull.Value ? null : propValue); 
        } 
        result.Add(item); 
       } 
      } 
      return result; 
     } 

/// <summary> 
/// Execute command return empty result 
/// </summary> 
public int ExecuteSqlCommand(string sqlCommand, Dictionary<string, object> @params) 
     { 
      List<SqlParameter> sqlParams = new List<SqlParameter>(); 
      foreach (var item in @params) 
      { 
       if (item.Value != null) 
        sqlParams.Add(new SqlParameter(item.Key, item.Value)); 
       else 
        sqlParams.Add(new SqlParameter(item.Key, DBNull.Value)); 
      } 

      if (@params.Count > 0) 
       sqlCommand += " "; 
      sqlCommand += String.Join(",", @params.Select(p => p.Key)); 
      return Context.Database.ExecuteSqlCommand(sqlCommand, sqlParams.ToArray()); 
     } 

/// <summary> 
    /// Execute stored procedure return set of rows 
    /// </summary> 
    public IEnumerable<TResult> ExecuteStoredProcedureWithRowsResult<TResult>(string name, Dictionary<string, object> @params) where TResult : class 
     { 
      //Fix exception: ExecuteReader requires the command to have a transaction when the connection assigned to the command is in a pending local transaction. The Transaction property of the command has not been initialized. 
      UnitOfWorkManager.Current.Options.IsTransactional = false; 
      using (var command = Context.Database.GetDbConnection().CreateCommand()) 
      { 
       var result = new List<TResult>(); 
       string sqlCmd = String.Format("{0} ", name); 
       if (command.Connection.State != System.Data.ConnectionState.Open) 
        command.Connection.Open(); 
       try 
       { 
        foreach (var item in @params) 
        { 
         if (item.Value != null) 
          command.Parameters.Add(new SqlParameter(item.Key, item.Value)); 
         else 
          command.Parameters.Add(new SqlParameter(item.Key, DBNull.Value)); 

         command.CommandText = sqlCmd; 
         command.CommandType = System.Data.CommandType.StoredProcedure; 
         using (var reader = command.ExecuteReader()) 
         { 
          result = MapToList<TResult>(reader); 
         } 
        } 
       } 
       catch (Exception ex) 
       { 
        throw ex; 
       } 
       finally 
       { 
        command.Connection.Close(); 
       } 

       return result; 
      } 
     } 

Et dans le service d'application, injectez votre référentiel personnalisé, et peut appeler la procédure stockée comme:

var @params = new Dictionary<string, object>(); 
@params.Add("Id", 1); 
var result = _customRepository.ExecuteStoredProcedureWithRowsResult<UserResult>("sp_getUsers", @params);