实体框架的依赖注入

时间:2016-07-13 11:20:35

标签: c# entity-framework dependency-injection inversion-of-control

我有两节课; '的批次'和' 项目' 一批包含许多项目。每个类都有一个私有dbContext,用于访问在类构造函数中注入的实体框架。

在UI类中,我想添加一个批次和多个项目,最后只调用一次SaveChanges(),如何制作?

public class Batch
{
  public int Id { get; set;}
  private readonly DatabaseModel  _dbModel;

  public Batch(DatabaseModel dbModel)
    {
        _dbModel = dbModel;
    }

  public bool AddBatch()
    {
      t_batch batch = new t_batch
       {
         id = Id
       };
      _dbModel.DbEntities.t_Batch.Add(batch);
      return true;
    }
}


public class Item
{
  public int Id { get; set;}
  public int BatchId { get; set; }

  private readonly DatabaseModel  _dbModel;

  public Item(DatabaseModel dbModel)
    {
        _dbModel = dbModel;
    }

  public bool AddItem()
    {
      t_item item = new t_item
       {
         id = Id,
         batchId = BatchId
       };
      _dbModel.DbEntities.t_item.Add(item);
      return true;
    }
}

在GUI类中:

using (DatabaseModel dbModel = new DatabaseModel)
{
  // Add Batch
  Batch batch = new Batch (dbModel)
     { Id = 1 };
  Batch.AddBatch();

  // Add Items
  Item item1 = new Item (dbModel)
   { Id = 1, BatchId = 1 };
  item1.AddItem();

  Item item2 = new Item (dbModel)
   { Id = 2, batchId = 1};
  item1.AddItem();

  dbModel.SaveChanges(); 
}

当我这样称呼时,数据库中没有添加任何内容,如何修复此问题而不是违反 DI / IOC

0 个答案:

没有答案