このコードを考えると:
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
q.Views ++;
db.SubmitChanges();
if (q.Views == 500)
{
// Call function
}
}
}
}
以下のように書いた方がよいでしょうか。
/// <summary>
/// Add to view count of this article
/// </summary>
public static void IncrementViewCount(int articleID)
{
var newViews = 0;
using (var db = new MainContext())
{
var q = (from c in db.tblArticles where c.ID == articleID select c).SingleOrDefault();
if (q != null)
{
newViews = q.Views + 1;
q.Views = newViews;
db.SubmitChanges();
}
}
if (newViews == 500)
{
// Call function
}
}
例 2 では、using ブロックが以前の時点で閉じられていることに注意してください。