书呆子晚餐模型是否使用最佳实践来处理对象?

发布于 2024-08-11 10:16:38 字数 928 浏览 2 评论 0原文

我一直在查看 Nerddinner 代码,他们在模型中做的一件事是创建一个实例DataContext 的如下所示:

public class DinnerRepository {

    private NerdDinnerDataContext db = new NerdDinnerDataContext();

    public IQueryable<Dinner> FindUpcomingDinners() {
        return from dinner in db.Dinners
            where dinner.EventDate > DateTime.Now
            orderby dinner.EventDate
            select dinner;
    }

    // more methods below
}

这些在控制器中使用如下:

public class DinnersController : Controller {
    DinnerRepository dinnerRepository = new DinnerRepository();

    public ActionResult Index() {
        var dinners = dinnerRepository.FindUpcomingDinners().ToList();
        return View("Index", dinners);
    }
}

但 NerdDinnerDataContext 似乎从未被释放。这是我应该担心的问题吗?或者这个模式可以吗?

注意:我知道这不是最新的书呆子晚餐代码

I've been looking at the Nerd Dinner code and one thing they do in their models, is create an instance of the DataContext like this:

public class DinnerRepository {

    private NerdDinnerDataContext db = new NerdDinnerDataContext();

    public IQueryable<Dinner> FindUpcomingDinners() {
        return from dinner in db.Dinners
            where dinner.EventDate > DateTime.Now
            orderby dinner.EventDate
            select dinner;
    }

    // more methods below
}

These are used in the controllers like this:

public class DinnersController : Controller {
    DinnerRepository dinnerRepository = new DinnerRepository();

    public ActionResult Index() {
        var dinners = dinnerRepository.FindUpcomingDinners().ToList();
        return View("Index", dinners);
    }
}

But it doesn't seem that NerdDinnerDataContext ever gets disposed. Is this a problem that I should worry about? Or is this pattern OK?

Note: not the latest Nerd Dinner code, I know

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏尔 2024-08-18 10:16:38

事实证明,在典型的应用程序中,处理 DataContext 对象通常不是您想要做的事情。

请参阅http://mostlytech.blogspot.com/2008/01/linq-datacontextdispose.html(当然是乔恩·斯基特)了解更多细节。

It turns out that disposing the DataContext object is generally not something you want to do in a typical application.

see http://mostlytech.blogspot.com/2008/01/linq-datacontextdispose.html (by Jon Skeet, of course) for a little more detail.

甜`诱少女 2024-08-18 10:16:38

在这种情况下,这是最佳实践。存储库正在返回一个 IQueryable 对象...这意味着查询的处理将被延迟,直到需要结果为止。

如果您释放存储库中的上下文,则当调用代码尝试从 IQueryable 对象检索结果时,将不会剩下任何 DataContext。

In this case, this is a best practice. The Repository is returning an IQueryable object...which means processing of the query will be delayed until the result is needed.

If you dispose of the context in the Repository, when the calling code tries to retrieve the results from the IQueryable object, there will be no DataContext left.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文