2013-04-09 103 views
0

我想將poco屬性傳遞給存儲過程(更新並添加對象) 對於早期版本的企業庫(例如v2.0),我可以這樣做:如何使用Enterprise-Library 5.0更新poco

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方法已經一去不復返了。

現在的問題是:如何獲取stored-proc參數並使用poco-properties-values填充這些參數?

回答

0

你可以做這樣的事情:

Database db = DatabaseFactory.CreateDatabase(); 

string spName = "MySP"; 
var parameters = new object[] { "Information", 22 }; 

int value = (int)db.ExecuteScalar(spName, parameters); 

現在,這依賴於參數順序。如果你想使用的名稱和自動填充的DbCommand和你的數據庫支持參數發現(如SQL服務器),那麼你可以這樣做:

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屬性名稱是相同的存儲過程參數名稱。