创建一个计划库,但在构造函数体中使用关键字 [英] Creating a plan repository, but using keyword in constructor body

查看:188
本文介绍了创建一个计划库,但在构造函数体中使用关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要访问的每一个方法的 planInfo LINQ变量的类。有没有办法做到这一点不删除using语句,并要求的Dispose()在每一个方法是什么?

I have a class that needs to access the planInfo LINQ variable in every method. Is there any way to do this without removing the using statement and calling Dispose() in every method?

我知道这样做的唯一方法就是把using语句在每一个方法,并从构造删除它,但毕竟是在重复where子句中的每一个方法,但我希望它保持不变。

The only other way I know to do it is to put the using statement in every method and removing it from the constructor, but that is repeating the where clause in every method but i want it constant.

public class PlanRepository
{
    private int _patientId = 0;
    private IQueryable<Plan> planInfo;

    public PlanRepository(int pid)
    {
        if (pid == 0) { UserAccess.RedirectToLogin(); }
        _patientId = pid;

        using (var db = new DbConn())
        {
            planInfo = db.Plans.Where(d => d.PatientId == _patientId);
        }
    }

    public int GetPulse()
    {
        return planInfo.Select(d => d.Pulse).FirstOrDefault();
    }

}

这code显然会引发错误的数据库连接被关闭了。

This code obviously throws an error that the db connection was closed.

推荐答案

只是兑现在构造函数列表:

Just materialize the list in the constructor:

planInfo = db.Plans.Where(d => d.PatientId == _patientId).ToList();

现在,该缓存中的数据(你不会看到任何数据库更新),但是如果你不想保持首位的数据库连接,这不应该是一个问题。

Now, that caches the data (you won't see any DB updates), but if you didn't want to maintain the DB connection in the first place, that shouldn't be an issue.

随着列表实现,所有其他功能都没有问题,使用它。

With the list materialized, all your other functions can use it with no problem.

这篇关于创建一个计划库,但在构造函数体中使用关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆