2013-03-05 83 views
0

我试图避免两次调用数据库。 我需要检查一条记录是否存在,如果是的话,然后用数据填充我的视图。 我有以下代码:重构 - 查看是否存在记录然后获取记录

 if (Presenters.PayeePresenter.GetByID(id) != null) 
     { 
      view = BLL.Presenters.PayeePresenter.GetByID(id); 

      msg.Success = true; 
      msg.Text = "Record Found"; 
     } 

我怎么能只是做调用数据库的最小金额是多少?

回答

6

将结果存储在变量中,并在分配属性之前检查它是否为null。

var obj = Presenters.PayeePresenter.GetByID(id); //Assuming this is database method call 
if (obj!= null) 
{ 
    //use obj.Properties to fill custom object or any additional logic 
    msg.Success = true; 
    msg.Text = "Record Found"; 
} 
+2

引入变量重构。 – SeeSharp 2013-03-05 01:22:13