1

在我的控制器中,我有一个方法正在创建一个模型来保存数据库中的一些信息,有没有办法在方法中创建一些逻辑来检查模型中是否已经有数据?每次用户导航到另一个页面时都会调用它SelectCompanyFromDropdown(),但为了减少我想检查的数据库调用。我想知道全局变量是否可以解决问题,但我知道您可能会在调试全局变量时遇到麻烦。

pseudo: 
if(Model != null)
Run Method
return PartialView(new model)
Else
return PartialView(existing model)

控制器方法:public PartialViewResult SelectCompanyFromDropdown() {

            var coid = Lt.GetThisUsersCoId();
            var model = new CompanyViewModel();
            using (var dc = new CompanyViewModelDbContext())
            {
                var content =
                    (from cr in db.CompanyRelationship
                     //This is grabbing all related companies to the logged in user
                     join c in db.Companies on cr.CoId equals c.CoId
                     where cr.PartnerCoId == coid

                     select new
                     {
                         cr.CoId,
                         c.CompanyName
                     }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName);

                model.Companies = content;

            }
            return PartialView(model);
        }

这是将模型发送到视图以创建下拉列表,但是我只想在每次用户更改页面时引用现有模型。

4

1 回答 1

1

如果您的数据库调用的结果不会经常更改,您可以缓存它。因此,首先编写一个将执行此任务的方法:

private IDictionary<int, string> GetCompanies(int coid)
{
    var result = MemoryCache.Default[coid.ToString()] as IDictionary<int, string>;
    if (result != null)
    {
        // we already have cached results => no need to perform expensive database calls
        // we can return directly the cached results;
        return result;
    }

    // there's nothing in the cache => we need to make the DB call
    // and cache the results for subsequent use
    using (var dc = new CompanyViewModelDbContext())
    {
        result =
            (from cr in db.CompanyRelationship
             //This is grabbing all related companies to the logged in user
             join c in db.Companies on cr.CoId equals c.CoId
             where cr.PartnerCoId == coid
             select new
             {
                 cr.CoId,
                 c.CompanyName
             }).Distinct().ToDictionary(cr => cr.CoId, c => c.CompanyName);
    }

    var policy = new CacheItemPolicy
    {
        // Cache the results of the Db query for 24 hours
        AbsoluteExpiration = DateTimeOffset.Now.AddHours(24),
        Priority = CacheItemPriority.NotRemovable,
    };

    MemoryCache.Default.Set(coid.ToString(), result, policy);

    return result;
}

现在您的控制器操作中剩下的就是调用此方法来填充您的视图模型:

var model = new CompanyViewModel();
var coid = Lt.GetThisUsersCoId();
model.Companies = GetCompanies(coid);
return PartialView(model);

此外,您似乎对视图模型有一些误解。您的 EF 上下文似乎被称为CompanyViewModelDbContext. 视图模型是专门为满足视图逻辑要求而设计的类。您的数据层(这是 EF 在您的案例中所扮演的角色)应该完全不了解此视图逻辑。你的领域模型不应该绑定到你的视图模型。

于 2013-10-04T22:00:28.220 回答