私のMVC5プロジェクトでは、このロジックをいくつかの方法で使用しています。それは動作しますが、私はかなり一貫して自分自身を繰り返しています。コントローラーメソッドを使用したDRY原理
private PersonnelManagementEntities db = new PersonnelManagementEntities();
private ActiveDirectoryTools adt = new ActiveDirectoryTools();
private ManagerService ms = new ManagerService();
private UserService us = new UserService();
private CompanyService cs = new CompanyService();
public ActionResult CompanySummary(int id = 0)
{
//Repeating logic begins here
int setID = 0;
adt.GetUserInfo(User.Identity.Name);
//Fetch current users company
User currentUser = us.getUser(adt.adUserName);
//Determine if user is a global manager or not. If global display all companies
ViewBag.Company = cs.FetchCompanies(currentUser);
//You can only see the companies you're assigned to, in the AllRequests window. Unless manually overwritten in the URL
if (currentUser.GlobalUser == true && id > 0)
{
setID = id;
}
else
{
setID = (int)currentUser.CompanyID;
}
//End of repeating logic
var resultSet = db.UserTimeSummaryUpdated(setID);
return View(resultSet.ToList());
}
私はこれを繰り返す回数を減らす最善の方法だと思いますか?
あなたが、私はこのコードを再利用する別の方法でここに見ることができます:
public ActionResult AllRequests(int id = 0)
{
int setID = 0;
adt.GetUserInfo(User.Identity.Name);
User currentUser = us.getUser(adt.adUserName);
ViewBag.Company = cs.FetchCompanies(currentUser);
//You can only see the companies you're assigned to, in the AllRequests window. Unless manually overwritten in the URL
if (id > 0)
{
setID = id;
}
else
{
setID = (int)currentUser.CompanyID;
}
ViewBag.EmployeeList = db.Users
.Where(x => x.disabled == false)
.Where(x => x.CompanyID == setID)
.OrderBy(x => x.FullName)
.ToList();
IQueryable timeRequests = db.TimeRequests
.Include(t => t.ApproveDenyReason)
.Include(t => t.DayType)
.Include(t => t.User)
.Include(t => t.User1)
.Include(t => t.User2)
.OrderByDescending(t => t.sDateTime)
.Where(t => t.User.CompanyID == setID);
return View(timeRequests);
}
私はのActionFilterを作成し、そのようにやって考えていたが、それはハックのようなものの代わりに行うための正しい方法と思われますもの。 私はまた、ユーザーがログインしたときの考えを楽しませました。私はユーザーオブジェクトを作成し、それをセッションを通して永続させます。 助けていただければ幸いです