将数据从读取器加载到对象中的更好方法是什么
看一下下面的代码,加载列表
while (dataReader.Read())
{
City city;
if (City.TryLoad(dataReader, out city))
{
defaultCities.Add(city);
}
}
TryLoad 读取读取器并加载数据对象,成功时返回 true,失败时返回 false。 有人告诉我,这样做的好处是,如果代码在加载对象时由于某种原因失败,代码不会抛出错误。因此,如果一行数据损坏,则不会将其添加到默认连接中。此外,在尝试加载中,我们可以记录抛出的特定行和错误并修复它。
另一方面,我之前遵循的方法只是加载对象并将它们添加到集合中。
while (dataReader.Read())
{
City city = new City();
city.Name = reader["Name"].ToString();
.
.
defaultCities.Add(city)
}
虽然第二种方法可能会由于数据库中的值损坏而失败,但您不希望这样吗?在第一种方法中,捕获由于缺失值而导致的错误是否会变得困难?
只是想了解其他人对这两种方法的优缺点的看法。
另外,请帮助适当地标记问题。
Have a look at the below code to Load a List
while (dataReader.Read())
{
City city;
if (City.TryLoad(dataReader, out city))
{
defaultCities.Add(city);
}
}
TryLoad reads the reader and loads the dataobject and returns true when successful and false when unsuccessful.
The benefit of this, I was told, was that the code would not throw an error if the code fails for some reason when loading the object. So if one row of data is corrupt, then that is not added to the default connection. Moreover, in the try load we can log which particular row threw and error and fix that.
On the other hand the approach which I followed earlier was simply loading the objects and adding them to the collection.
while (dataReader.Read())
{
City city = new City();
city.Name = reader["Name"].ToString();
.
.
defaultCities.Add(city)
}
While the second approach may fail due to corrupt value in the database, wouldn't you want that? Wont catching bugs due to a missing value become difficult in the first approach?
Just wanted the opinion of others on the pros cons of the two approaches.
Also, please help in tagging the question appropriately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
第二个。我喜欢它,因为它更干净,更容易维护。
您还可以将数据直接从数据读取器加载到变量中,并在加载到类中之前进行测试 - DateTimes 是很好的例子,我建议对其使用 TryParse() :
DateTime contentLastModified;
if (!DateTime.TryParse(dr["LastModified"].ToString(), out contentLastModified))
{
contentLastModified = MyApp.Common.Constants.SystemTypeValues.NullDate;
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如果您可以允许对错误数据引发异常,则第二种方法是最好的。这在管理员可以控制数据质量的情况下很常见。
然而,管理员通常无法保证数据的质量。在这些情况下,通常要求应用程序妥善处理格式错误的数据。当面对这种需求时,第一种方法是一种优雅的方法。
If you can permit an exception to be thrown on bad data, the second approach is best. This is common in situations where the administrators have control of the quality of the data.
However, it's often true that the administrators can't guarantee the quality of the data. In these cases, it's frequently a requirement that the application handle malformed data gracefully. When faced with this need, the first approach is an elegant way to do that.