nHibernate - 迭代类的属性以通常为存储过程添加参数
我想要一个类来定义存储过程的参数数据。它将是一个非常简单的对象:
public class MyQueryData : SprocObjectBase
{
public int Value1 { get; set; }
public string Value2 { get; set; }
public bool Value3 { get; set; }
...
}
它将继承自具有共享值(例如名称)的基类。
public abstract class SprocObjectBase
{
public string SprocName { get; set; }
}
简单类型,易于转换。但是,这些对象将不止一个,而且每个对象都不同。
然后,我希望能够迭代对象的属性并将参数值添加到我的查询中,假设属性名称是我的存储过程参数名称。所以,我的代码看起来像这样:
public void Execute<T>(T entity) where T : SprocObjectBase
{
IQuery query = Session.GetNamedQuery(entity.SprocName);
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
//??????????????
}
query.ExecuteUpdate();
}
我的问题是,如何将 query.SetParameter<>()
与 foreach 循环中的属性信息一起使用,以将每个属性作为参数添加到存储过程?
编辑: 我当前的用法(无法编译)如下所示:
query.SetParameter<prop.GetType()>(prop.Name, prop.GetValue(entity, null));
I want to have a class that defines my parameter data for a stored procedure. It's going to be a very simple object:
public class MyQueryData : SprocObjectBase
{
public int Value1 { get; set; }
public string Value2 { get; set; }
public bool Value3 { get; set; }
...
}
It will inherit from a base class with shared values, like the name.
public abstract class SprocObjectBase
{
public string SprocName { get; set; }
}
Simple types for easy conversion. But, there will be more than one of these objects, and each one different.
Then, I want to be able to iterate the properties of the object and add the parameter values to my query, assuming the property names are my sproc parameter names. So, my code looks something like this:
public void Execute<T>(T entity) where T : SprocObjectBase
{
IQuery query = Session.GetNamedQuery(entity.SprocName);
var properties = typeof(T).GetProperties();
foreach (var prop in properties)
{
//??????????????
}
query.ExecuteUpdate();
}
My question is, how do I use query.SetParameter<>()
with the property info inside my foreach loop to generically add each property as a parameter to the stored procedure?
EDIT:
My current usage, which does not compile, looks like this:
query.SetParameter<prop.GetType()>(prop.Name, prop.GetValue(entity, null));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我没有尝试,但这样的事情应该可以工作:
顺便说一句,到目前为止,您不需要使该方法通用。无论如何,你都在使用反射。
I didn't try, but something like this should work:
By the way, until now you don't need to make the method generic. You are using reflection anyway.