数据库条目更改时对象数据不更新

时间:2014-06-16 12:57:45

标签: asp.net-mvc-3 razor

我的网站有一个横幅,可以在紧急/特殊情况下向访问者显示消息。横幅显示基于对数据库表的调用,该表根据DateTime.Now对象检查开始/结束时间。

static private PublicWebEntities db = new PublicWebEntities(); public IEnumerable<AlertMsg> CurrentAlert() { var alerts = from q in db.AlertMsgs where (q.Start < DateTime.Now && q.Finish > DateTime.Now) select q; return alerts; }

并在页面中显示

@if (Model.CurrentAlert().Any()){           
<div class="alert-block">
    <a href="" class="button-close">X</a>
    @foreach (var item in Model.CurrentAlert())  {
        <p>
        @Html.Raw(item.Message)
        </p>  }
</div>}

如果我更改记录中的开始或结束时间,横幅将关闭。但是,当更新记录的文本消息时,显示是旧消息的缓存副本。

我在这个网站上使用EF 4.1和MVC3。

1 个答案:

答案 0 :(得分:1)

由于服务器正在缓存页面,因此您可以使用OutputCache属性来控制保留多长时间来存储页面。

使用以下命令将“关闭”缓存:

[OutputCache(Location = OutputCacheLocation.None, NoStore = false, Duration = 0)]
public ActionResult Index(){
    //Your code
}

这应该禁用您正在调用的操作来填充缓存中的结果。

为每个会话请求使用基本控制器(在评论中提出)

让控制器控制上下文生命周期的一个例子

/// <summary>
/// Provides a base implementation for controllers using a single, simple common context
/// </summary>
public class BaseController : Controller
{
    public MyDbContext Db { get; set; }

    public BaseController()
    {
        Db = new MyDbContext();
    }

    /// <summary>
    /// Manages saving the changes back to the database.  This should be performed per action and you shouldn't have to manage it
    /// </summary>
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (Db.ChangeTracker.HasChanges()) Db.SaveChanges();

        base.OnActionExecuted(filterContext);
    }

    /// <summary>
    /// Release the resources the context uses and close connections if needed
    /// </summary>
    protected override void Dispose(bool disposing)
    {
        if(Db != null) Db.Dispose();

        base.Dispose(disposing);
    }
}
相关问题