处理 DBNull 的通用方法
使用 SqlDataReader 时,我的代码中有很多此类逻辑 有没有更干净、更通用的方法来处理这个问题?
if (reader["VisitingAddressId"] != DBNull.Value)
{
visitingAddress = new Address()
{
AddressId = Convert.ToInt64(reader["VisitingAddressId"]),
Address1 = reader["VisitingAddress"].ToString(),
AddressType = AddressType.VisitingAddress,
PostalCode = reader["VisitingPostal"].ToString(),
PostalDistrict = reader["VisitingPostalDistrict"].ToString()
};
}
if (reader["PostalAddressId"] != DBNull.Value)
{
postalAddress = new Address()
{
AddressId = Convert.ToInt64(reader["PostalAddressId"]),
Address1 = reader["PostalAddress"].ToString(),
AddressType = AddressType.PostalAddress,
PostalCode = reader["PostalPostal"].ToString(),
PostalDistrict = reader["PostalPostalDistrict"].ToString()
};
}
I have a lot of this type of logic in my code when using the SqlDataReader
Is there a cleaner more generic way to handle this?
if (reader["VisitingAddressId"] != DBNull.Value)
{
visitingAddress = new Address()
{
AddressId = Convert.ToInt64(reader["VisitingAddressId"]),
Address1 = reader["VisitingAddress"].ToString(),
AddressType = AddressType.VisitingAddress,
PostalCode = reader["VisitingPostal"].ToString(),
PostalDistrict = reader["VisitingPostalDistrict"].ToString()
};
}
if (reader["PostalAddressId"] != DBNull.Value)
{
postalAddress = new Address()
{
AddressId = Convert.ToInt64(reader["PostalAddressId"]),
Address1 = reader["PostalAddress"].ToString(),
AddressType = AddressType.PostalAddress,
PostalCode = reader["PostalPostal"].ToString(),
PostalDistrict = reader["PostalPostalDistrict"].ToString()
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我在数据服务类中有这些辅助方法(您可以将它们设为静态):
然后在映射代码中,您只需执行以下操作:
I have these helper methods in a data service class (you could make them both static):
Then in your mapping code, you just do:
您可以使用像 Dapper 这样的微型 ORM:http://code.google.com/ p/dapper-dot-net/
多重映射功能将消除所有样板代码。
You could use a micro-ORM like Dapper: http://code.google.com/p/dapper-dot-net/
The multi mapping functionality would eliminate all that boiler plate code.
你指的是ORM,ORM有很多。 NHibernate、实体框架,甚至 ADO.NET(您已经在使用)都支持关系数据集,尽管在这种情况下您通常必须使用 DataSet 或派生的强类型类。
查看此处的 .NET 部分以获取列表:
http://en.wikipedia.org/wiki/ List_of_object-relational_mapping_software
您有什么要求?也许我们可以缩小范围。
What you are referring to are ORMs, of which there are many. NHibernate, Entity Framework, even ADO.NET (which you are already using) has support for relational datasets, although in that case you usually have to use a
DataSet
or derived, strongly-typed classes.Check out the .NET section here for a list:
http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software
What are you requirements? Maybe we can narrow it down.