Let's say I have a class
public class foo { public string FooId { get; set; } }
Now in my Data layer, I am trying to write code which will create one instance of IDataCommand and set FooId as on of the command parameters something like this
public void save(foo f, IDbConnection conn)
{
IDataCommand cmd = conn.CreateCommand();
cmd.CommandName = "SP_SAVE_INFO" ;
IDataDbParameter param = cmd.CreateParameter();
param.name = "@fooId";
param.value=(f.id>0)?f.id:(object)DbNull.Value;
cmd.parameters.add(param);
cmd.ExecuteNonQuery();
}
If you notice code line - param.value=(f.FooId >0)?f.id:(object)DbNull.Value; . My question is exactly in this area. If I have too many parameters to be provided. It looks kind of bad when I check for value like this on every parameter.开发者_JAVA技巧 Question here is what is the best way to do this kind of thing? Who should do that DL or BL? If BL, then should it assign DBNull Value there? Is there any other standard way of doing this?
Why not try a generic extension method?
public static class IDataDbParameterExtensions
{
public static void SetValue<T>(this IDataDbParameter parameter, T value)
{
if(value == default(T)) // for structs (ValueTypes) like Int, default(T) will be 0 and for classes (RefTypes), it will be null.
{
parameter.Value = DBNull.Value;
}
else
{
parameter.Value = value;
}
}
}
Use it like following:
param.SetValue(f.id);
The most complete solution is not to do this yourself. There are many frameworks out there that will help you here - take a look at NHibernate or Entity Framework for instance.
If you really need to do this manually then you could refactor the checks into reusable methods. Something like this:
public void AddIntParameterWithNullForZero(IDataCommand command, string parameterName, int parameterValue)
{
// Add the parameter and perform the checks here.
}
精彩评论