使用DataContext进行许多操作

时间:2011-08-23 17:23:10

标签: entity-framework linq-to-sql design-patterns

我正在使用EF进行开发,这里有足够的新功能。 当我必须对上下文执行不同的操作时,我对如何使用EntityFramework上下文感到困惑。你能给我一些很好的教程并浏览我的代码来找到可能的问题

现在我有下一个代码

//domain.dll

class OrderDomainService 
{
   public void DoWork()
   {
     foreach(var order in GetOrders())
    {
       DeleteOrder(order);
    }

   }
   public List<Order> GetOrders()
   {
      IOrderRepository orderRep = new OrderRepository();
      return orderRep.GetAll();
   }

 public void DeleteOrder(Order order)
   {
      IOrderRepository orderRep = new OrderRepository();
      return orderRep.Delete(order);
   }
}

//repository.dll

public interface IOrderRepository
{
   List<Order> GetAll();

   void Delete(Order order);

   void SaveContext()
}

public class OrderRepository
{
 public OrderRepository()
{
   if (ctx == null) 
    ctx = new EntityFrameworkDataContext();
}

   static EntityFrameworkDataContext ctx { get; set; }

   public List<Order> GetAll()
   {
      return ctx.Orders;
   }

   public void Delete(Order order)
   {
      ctx.Orders.Delete(order);
   }

   public void SaveContext()
   {
     ctx.SaveChanges();
     ctx = null;
   }
}

1 个答案:

答案 0 :(得分:1)

您需要在多个存储库之间共享相同的EntityFrameworkDataContext实例(使用工作单元模式http://blogs.msdn.com/b/adonet/archive/2009/06/16/using-repository-and-unit-of-work-patterns-with-entity-framework-4-0.aspx)。因为如果您正在执行需要启动两个或更多存储库的操作,您将拥有问题。