首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Enterprise-Library 5.0更新poco

如何使用Enterprise-Library 5.0更新poco
EN

Stack Overflow用户
提问于 2013-04-09 16:53:57
回答 1查看 274关注 0票数 0

我想将poco属性传递给一个存储过程(更新并添加对象),使用较早版本的Enterprise Library (如v2.0),我可以这样做:

代码语言:javascript
复制
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方法已不复存在。

问题是:如何获取存储的proc参数并使用poco-properties-value填充这些参数?

EN

回答 1

Stack Overflow用户

发布于 2013-06-13 01:47:11

你可以这样做:

代码语言:javascript
复制
Database db = DatabaseFactory.CreateDatabase();

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

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

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

代码语言:javascript
复制
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);
代码语言:javascript
复制
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属性名称与存储过程参数名称相同。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15897489

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档