繁体   English   中英

具有工作单元和通用存储库的原始操作

[英]Crud operations with unit of work and generic repository

我正在使用Ninject for DI在带有unitofwork和通用存储库的mvc 4.0中进行粗操作。 我可以从表中获取特定记录,甚至可以从表中获取所有记录。 但是我无法在数据库表中插入新记录。 我没有收到任何错误/异常,它正在干净地运行每个语句,但是在数据库中没有任何作用,下面是我使用存储库和unitof工作的控制器。 有人可以告诉我我在哪里或在这段代码中留下了哪些代码/声明。 我已经检查了很多时间,现在被困住了。 没有解决问题

控制器:

 private IUnitOfWork _unitOfWork;
    private IRepository<tbl_Employee> _Repo;
    private IRepository<tbl_Department> _Department;

    public HomeController( IUnitOfWork UOW, IRepository<tbl_Employee> Repository, IRepository<tbl_Department> Depart)
    {   
        this._unitOfWork = UOW;
        this._Repo = Repository;
        this._Department = Depart;
    }


       //This runs successfully and gets all the records in the view page and I am displaying all records using foreach in div structure



 public ActionResult Index()
    {
        EmployeeModel ObjModel = new EmployeeModel();
        ObjModel.Employees = this._Repo.GetALL();
        //ObjModel.Employees = this._Employee.GetEmployees();
        return View(ObjModel);
    }

//This also runs successfully and it brought me a single record on selection of particular record from employee listing.



    public ActionResult EmployeeDetail(string id)
            {
                EmployeeDetailModel ObjModel = new EmployeeDetailModel();
                if (!string.IsNullOrEmpty(id))
                {
                    var Employee = this._Repo.Find(Convert.ToInt32(id));
                    if (Employee != null)
                    {
                        ObjModel.InjectFrom(Employee);
                    }
                }
                return View(ObjModel);
            }

// Here is the problem . Not able to insert the record. The model object is not empty . I have checked it and there is no error.It brought me  a message 
  "Employee Created Successfully but in database there is no record.



    public ActionResult SaveEmployee(EmployeeDetailModel Model)
            {
                string Msg = string.Empty;
                try
                {
                    tbl_Employee ObjEmployee = new tbl_Employee();
                    ObjEmployee.InjectFrom(Model);
                    if (Model.Male)
                    {
                        ObjEmployee.Sex = "m";
                    }
                    else
                    {
                        ObjEmployee.Sex = "f";
                    }
                    ObjEmployee.Department_Id = Model.Dept_id;
                    ObjEmployee.Salary = Convert.ToInt32(Model.Salary);
                    this._Repo.Insert(ObjEmployee);
                    this._unitOfWork.Commit();
                    Msg = "Employee Created Successfully";
                }
                catch
                {
                    Msg = "Error occurred while creating the employee, Please try again.";
                }
                return Json(new { Message = Msg });
            }

/// Repository interface



     public interface IRepository<T> where T : class
        {
            void Insert(T entity);
            void Delete(T entity);
            void Update(T entity);
            T Find(int key);
            IEnumerable<T> GetALL();
        }

储存库类

 public class Repository<T> : Connection, IRepository<T> where T : class
        {
            private readonly DbSet<T> _dbSet;

            public Repository()
            {
                _dbSet = _dbContext.Set<T>();
            }

            public void Insert(T entity)
            {
                _dbSet.Add(entity);
            }
            public void Delete(T entity)
            {
                _dbSet.Remove(entity);
            }
            public void Update(T entity)
            {
                var updated = _dbSet.Attach(entity);
                _dbContext.Entry(entity).State = EntityState.Modified;
                //_dataContext.Entry(item).State = EntityState.Modified;
            }
            public T Find(int Key)
            {
                var dbResult = _dbSet.Find(Key);
                return dbResult;
            }
            public IEnumerable<T> GetALL()
            {
                return _dbSet;
            }
        }

工作单元界面

  public interface IUnitOfWork : IDisposable
        {
            void Commit();
        }

 Unit of work class

public class UnitOfWork : Connection, IUnitOfWork
    {
        private bool _disposed;
        public void Commit()
        {
            _dbContext.SaveChanges();
        }
        public void Dispose()
        {
            Dispose(true);

            // Take yourself off the Finalization queue to prevent finalization code for object from executing a second time.
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (!_disposed)
            {
                // If disposing equals true, dispose all managed and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (_dbContext != null)
                    {
                        _dbContext.Dispose();
                    }
                }
            }

            _disposed = true;
        }
    }

我的UnitofWork和Repository类从定义dbcontext的连接类派生。

 public abstract class Connection
    {
        protected db_TestEntities _dbContext;
        public Connection()
        {
            this._dbContext = new db_TestEntities();
        }
    }

是我的dbContext每次都在创建一个新实例,就像这里解释的那样

如果是的话,我该如何解决。

tbl_Employee ObjEmployee = new tbl_Employee();
ObjEmployee.InjectFrom(Model);
if (Model.Male)
{
    ObjEmployee.Sex = "m";
}
else
{
    ObjEmployee.Sex = "f";
}
ObjEmployee.Department_Id = Model.Dept_id;
ObjEmployee.Salary = Convert.ToInt32(Model.Salary);
this._Repo.Insert(ObjEmployee);

之后,您应该看到EF在本地内存中映射了您的对象。

this._unitOfWork.Commit();

在这里,您的对象应该被推送到数据库。 dbContext.SaveChanges()返回更改的记录数,在您的情况下应该为1。

Msg = "Employee Created Successfully";

更新:所以问题出在您建议的Connection类中。

我将在一个地方创建DbContext,然后将其传递到存储库和工作单元。 您还可以在工作构造器单元中创建DbContext,然后将UOW传递到存储库。 这是我对此的较早实现:

public class EntityFrameworkUnitOfWork : IUnitOfWork
{
    private ForexDbContext dbContext;

    internal ForexDbContext DbContext
    {
        get { return dbContext ?? (dbContext = new ForexDbContext()); }
    }

    internal DbSet<T> Set<T>()
    where T : class
    {
        return DbContext.Set<T>();
    }

    public void Dispose()
    {
        if(dbContext == null) return;

        dbContext.Dispose();
        dbContext = null;
    }

    public void SaveChanges()
    {
        int result = DbContext.SaveChanges();
    }

    public ITransaction BeginTransaction()
    {
        return new EntityFrameworkTransaction(DbContext.BeginTransaction());
    }
}
public class ContactsRepositoryWithUow : IRepository<Contact>
{
    private SampleDbEntities entities = null;

    public ContactsRepositoryWithUow(SampleDbEntities _entities)
    {
        entities = _entities;
    }

    public IEnumerable<Contact> GetAll(Func<Contact, bool> predicate = null)
    {
        if (predicate != null)
        {
            if (predicate != null)
            {
                return entities.Contacts.Where(predicate);
            }
        }

        return entities.Contacts;
    }

    public Contact Get(Func<Contact, bool> predicate)
    {
        return entities.Contacts.FirstOrDefault(predicate);
    }

    public void Add(Contact entity)
    {
        entities.Contacts.AddObject(entity);
    }

    public void Attach(Contact entity)
    {
        entities.Contacts.Attach(entity);
        entities.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
    }

    public void Delete(Contact entity)
    {
        entities.Contacts.DeleteObject(entity);
    }       
}

请在下面的链接中找到答案以获取更多详细信息

使用UnitOfWork进行粗体操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM