如何使用存储库模式将两个实体保存在一起

时间:2016-08-14 20:18:26

标签: entity-framework asp.net-mvc-5

这是我的IGenericRepository

public interface IGenericRepository<T>
{
    IEnumerable<T> GetAll();
    IEnumerable<T> GetMany(Func<T, bool> predicate);
    void Insert(T obj);
    void Save();

}

这是它的实现

public class GenericRepository<T> : IGenericRepository<T> where T : class
{
    private ApplicationDbContext db;
    private DbSet<T> table = null;

    public GenericRepository(ApplicationDbContext db)
    {
        this.db = db;
        table = db.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {                           
        return table.ToList();
    }

    public IEnumerable<T> GetMany(Func<T, bool> predicate)
    {
        var data=table.Where(predicate);
        return data;
    }

    public void Insert(T obj)
    {
        table.Add(obj);
    }


    public void Save()
    {
        db.SaveChanges();
    }
}

以下是Department

的存储库类
public interface IDepartmentRepository : IGenericRepository<Department>
{
    IEnumerable<Department> GetAlldepartment();


    void Save1();
}

public class DepartmentRepository : GenericRepository<Department>, IDepartmentRepository
{
    private ApplicationDbContext db;

    public DepartmentRepository(ApplicationDbContext db):base(db)
    {
        this.db = db;
    }

    public IEnumerable<Department> GetAlldepartment()
    {
       var v= from c in db.Departments
                select c;

        return v;
    }



    public void Save1()
    {
        db.SaveChanges();
    }

}

同样,我有Customer

的另一个存储库
public interface ICustomerRepository : IGenericRepository<Customer>
{
    IEnumerable<Customer> SelectAll();
    void Update(Customer obj);
    void Delete(string id);


}

public class CustomerRepository : GenericRepository<Customer>, ICustomerRepository
{
    private ApplicationDbContext db;

    //public CustomerRepository()
    //{
    //    this.db = new ApplicationDbContext();
    //}

    public CustomerRepository(ApplicationDbContext db)
        : base(db)
    {
        this.db = db;
    }

    public IEnumerable<Customer> SelectAll()
    {
        var data = this.GetMany(a => a.Id == 1);

        return data;
    }      

    public void Update(Customer obj)
    {
        db.Entry(obj).State = EntityState.Modified;
    }

    public void Delete(string id)
    {
        Customer existing = db.Customers.Find(id);
        db.Customers.Remove(existing);
    }

}

最后我的控制器

public class DepartmentController : Controller
{
    DepartmentRepository _departmentRepository=null;
    ICustomerRepository _customerRepository=null;
    ApplicationDbContext _context = new ApplicationDbContext();
    public DepartmentController()
    {
        this._departmentRepository = new DepartmentRepository(_context);
        this._customerRepository = new CustomerRepository(_context);
    }


    public ActionResult Index()
    {
        var data = _departmentRepository.GetAlldepartment();
        return View(data);
    }
    public ActionResult Create()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Create(Department Department)
    {
        _departmentRepository.Insert(Department);

        List<Customer> list = new List<Customer>();
        for (int i = 0; i < 5; i++)
        {
            list.Add(new Customer
            {
                Id = i,
                Name = i + " Hi"

            });
            _customerRepository.Insert(list[i]);
        }
        _departmentRepository.Save();
        return RedirectToAction("Index");
    }
    protected override void Dispose(bool disposing)
    {

        base.Dispose(disposing);
    }
}

如果我想从Department保存CustomerDepartmentController,那么我只需创建一个DBcontext对象的实例,并将同一个对象传递给两个存储库类。有什么问题吗?如果是这样,请帮助我如何做到这一点。

1 个答案:

答案 0 :(得分:0)

在ActionFilter中创建一个TransactionScope并将其放在您的控制器操作

[AttributeUsage(AttributeTargets.Method)]
public class TransactionScopeAttribute : ActionFilterAttribute
{
    private TransactionScope TransactionScope { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        TransactionScope =
            new TransactionScope(TransactionScopeOption.Required, new TransactionOptions
            {
                IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
            });
    }
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (TransactionScope == null)
            return;

        if (filterContext.Exception == null)
        {
            TransactionScope.Complete();
            return;
        }

        TransactionScope.Dispose();
    }
}