【问题标题】:EntityFramework Multiple Queries Multiple DataContexts? Multiple Connections?EntityFramework 多个查询多个 DataContexts?多个连接?
【发布时间】:2017-08-16 09:54:33
【问题描述】:

我是 EF 新手,我第一次需要同时执行多个查询,假设我的 BLL 和 DAL 由 EF 生成,我还有一个 viewModel,在 BLL 上我是像这样引用 DAL 并检索数据:

public Decimal getPrice()
    {
        Decimal x = 0;
        siliconContext = new DAL.Entities();
        var result = from d in siliconContext.SILICONs
                     select d.MIN_PRICE;
        foreach (Decimal d in result)
        {
            x = d;
        }
        return x;
    }

一切都好,在 viewModel 上我只使用了这两行代码:

Silicon sil = new Silicon();
Price = sil.getPrice();

我假设上下文将处理连接、打开连接、执行某些操作然后关闭它,但现在我的 ViewModel 中我将引用两个 BLL,它们将引用两个 DAL 和当然在同一个方法中有两个不同的上下文,谁来管理这个? EF 4 是否足够聪明,可以只打开一个连接并让两个或更多上下文完成它们的工作,然后关闭连接?这是我的 viewModel 的外观示例

Silicon sil = new Silicon();
Price = sil.getPrice();
Glass gl = new Glass();
GlassPrice = gl.getPrice();

【问题讨论】:

    标签: c# wpf entity-framework


    【解决方案1】:

    首先你需要关闭 DataContext 的连接。

    public Decimal getPrice()
    {
        Decimal x = 0;
        using (DAL.Entities siliconContext = new DAL.Entities())
        {
            var result = from d in siliconContext.SILICONs
                         select d.MIN_PRICE;
            foreach (Decimal d in result)
            {
                x = d;
            }
            return x;
        }
    }
    

    其次,如果您想从两个表中获取数据,请执行以下操作。

    public Decimal getPrice()
    {
        Decimal x = 0; 
        using (DAL.Entities siliconContext = new DAL.Entities())
        {
            var result = from d in siliconContext.SILICONs
                         select d.MIN_PRICE;
    
            var result2 = from d in seliconContext.GLASEs
                          select d.MIN_PRICE;
    
            //You can then work with results from table GLASE!
    
            foreach (Decimal d in result)
            {
                x = d;
            }
            return x;
        }
    }
    

    【讨论】:

    • 感谢您的回复,我只有一个数据库,在我的示例中,我试图从两个表中检索 Silicon 和 Glass,我了解您的第一个代码 sn-p,但第二个没有t 回答我的问题,你是说只有一个数据库和多个表我仍将使用一个上下文? ,那我该怎么做呢?完成我最后的代码 sn-p ?
    • 同意,我现在明白了一些新的东西,但仍然请看我帖子中的最后一个代码,我有两个不同的类(硅和玻璃),每个类都会引用它的 DAL 类,每个 DAL 类都会自己连接到数据库,因为每个类都会执行自己的 getPrice() 方法,这意味着两个不同的连接,连接会一个接一个地打开和关闭,出于性能考虑,这并不好,我想这是一个设计问题但是我不确定,希望你明白我的意思
    • 是的,你有点担心总是打开和关闭与数据库的连接。我个人更喜欢这种方法,可以说,连接的生命周期对于特定的工作单元来说只是“活着”的。我不会太在意性能。 Ragzitsu 还展示了一个非常好的链接,可以帮助解释您遇到的大多数问题。希望这会有所帮助。
    【解决方案2】:

    您需要管理对象上下文的生命周期,以便正确初始化和处置它们。有关上下文生命周期管理的优秀资源,请参阅 http://blogs.msdn.com/b/alexj/archive/2009/05/07/tip-18-how-to-decide-on-a-lifetime-for-your-objectcontext.aspx

    【讨论】:

    • 感谢链接,一会儿去看看
    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    相关资源
    最近更新 更多