我使用的是asp.net mvc和nhibernate工作模式的單元。我應該如何設計? Nhibernate工作單元中的一種方法
我有這樣的事情
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
return false;
}
return true;
}
所以在我的if語句,如果事情是零,我需要它不爲空我剛走出語句。
這是相反的嵌套if語句可能像嵌套4或5次做空檢查。
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff != null)
{
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse != null)
{
// some more check heere (could have another few if statements null checks here)
}
}
}
因此,我發現第一種方法更容易閱讀嵌套級別的if語句。
我的問題是,即使你在nhibernate中做了一個查詢,你也要必須把它包裝在一個事務中,最後做一個回滾或提交。
選項1
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
unitOfWork.Commit();
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
unitOfWork.Commit();
return false;
}
unitOfWork.Commit();
return true;
}
這樣,你必須一直把承諾無論我不喜歡。如果可能的話我希望只有一個提交(除非我有工作事務的多個單元)
於是我雖然爲什麼不把它放在最後這樣
public bool IsSomething()
{
try
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
return false;
}
return true;
}
catch(Exception ex)
{
unitOfWork.RollBack();
}
finally
{
unitOfWork.Commit();
}
}
我喜歡這一點,但那麼我意識到如果提交失敗會發生什麼?它不會回滾,異常不會被捕獲。
那麼其他人有什麼想法?
你只讀還是你更新/插入也? – Firo
取決於一些可能有讀/更新/插入混合的方法,或者有些可能只是讀取。 – chobo2