【问题标题】:Entity Framework: using the same instance of the model across methods?实体框架:跨方法使用模型的相同实例?
【发布时间】:2013-12-12 18:46:28
【问题描述】:

我正在开发一个使用 Web 服务并通过 EF4 将数据直接推送到 SQL Server 2008 数据库的应用程序。我需要打破从 WS 中拉取数据、更新 SQL 中的记录以及删除 WS 中不再存在的 SQL 记录的过程,因为 WS 本身有时可能非常不稳定,而且事实证明它更简单、更容易如果我使用单独的方法来处理重试某些步骤而不是尝试将其全部塞进一个方法中,请进行故障排除。

我的问题是:当我创建模型的一个实例(MyEntities context = new MyEntities())时,我可以将它传递给其他方法,以避免两个不同实例尝试以不同的方式更新数据库的问题并相互覆盖?如果答案是肯定的,我该怎么做?

我在想我应该将它添加为带有 ref 关键字的参数,a la:

MyEntities context = new MyEntities();
CallSomeOtherMethod(ref context, otherinfo);

internal static void CallSomeOtherMethod(ref MyEntities entity, String[] otherinfo)
{
    entity.DoSomething();
...

想法?

【问题讨论】:

    标签: c# entity-framework entity-framework-4


    【解决方案1】:

    首先,不需要ref,只有当您计划将上下文替换到方法内的另一个上下文时才需要。

    其次,在课堂层面思考,你处于面向对象的世界。这意味着您不会将 db 上下文传递给单个方法,而是传递给具有特定职责的类。

    public class SomeService
    {
        private DbContext _context;
    
        public SomeService ( DbContext ctx )
        {
            this._context = ctx;
            ...
        }
    
       // now, context is available for all methods inside the class
    

    然后

       // pass existing context
       SomeService service = new SomeService( context );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2017-06-30
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      相关资源
      最近更新 更多