【问题标题】:How to update a poco with Enterprise-Library 5.0如何使用 Enterprise-Library 5.0 更新 poco
【发布时间】:2013-04-09 08:53:56
【问题描述】:

我想将 poco 属性传递给存储过程(更新并添加对象) 使用早期版本的企业库(例如 v2.0),我可以执行以下操作:

var arrParam = SqlHelperParameterCache.GetSpParameterSet(ConnectionString(), 
                   SprocNameSet);

for (int x = 0; x <= arrParam.Length - 1; x++)
{           
    System.Reflection.PropertyInfo pi = 
        dataObject.GetType()
        .GetProperty(arrParam[x].ParameterName
          .Substring(1, Convert.ToInt32(arrParam[x].ParameterName.Length) - 1));        
    arrParam[x].Value = pi.GetValue(myDataObject, null);
}

SqlHelper.ExecuteScalar(ConnectionString(), 
    CommandType.StoredProcedure, 
    SprocNameSet, 
    arrParam); 

但在 5.0 版(可能更早?)中,SqlHelperParameterCache.GetSpParameterSet 方法已消失。

问题是:如何获取存储过程参数并用 poco-properties-values 填充它们?

【问题讨论】:

    标签: c# .net stored-procedures enterprise-library poco


    【解决方案1】:

    你可以这样做:

    Database db = DatabaseFactory.CreateDatabase();
    
    string spName = "MySP";
    var parameters = new object[] { "Information", 22 };
    
    int value = (int)db.ExecuteScalar(spName, parameters);
    

    现在,这取决于参数顺序。如果您想使用名称并自动填充 DbCommand 并且您的数据库支持参数发现(例如 SQL Server),那么您可以执行以下操作:

    public class MyClass
    {
        public string Severity { get; set; }
        public int OtherValue { get; set; } 
    
    }
    
    MyClass myClass = new MyClass() { OtherValue = 1, Severity = "Information" };
    
    Database db = DatabaseFactory.CreateDatabase();
    
    string spName = "MySP";            
    DbCommand cmd = db.GetStoredProcCommand(spName);
    
    db.PopulateCommandValues(cmd, myClass); 
    
    int value = (int)db.ExecuteScalar(cmd);
    
    public static class DatabaseExtensions
    {
        public static void PopulateCommandValues<T>(this Database db, 
            DbCommand cmd, T poco)
        {
            if (!db.SupportsParemeterDiscovery)
            {
                throw new InvalidOperationException("Database does not support parameter discovery");
            }
    
            db.DiscoverParameters(cmd);
    
            foreach (DbParameter parameter in cmd.Parameters)
            {
                if (parameter.Direction != System.Data.ParameterDirection.Output &&
                    parameter.Direction != System.Data.ParameterDirection.ReturnValue)
                {
                    PropertyInfo pi = poco.GetType().GetProperty(
                        parameter.ParameterName.Substring(1)); // remove @ from parameter
    
                    if (pi != null)
                    {
                        parameter.Value = pi.GetValue(poco, null);
                    }
                }
            }
        }
    }
    

    这假定 POCO 属性名称与存储过程参数名称相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 2023-04-04
      • 2012-02-18
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2011-08-27
      相关资源
      最近更新 更多