简体   繁体   中英

Crud operations with unit of work and generic repository

I am working on crud operations in mvc 4.0 with unitofwork and generic repository with Ninject for DI. I am able to get a particular record from a table, I am even able to get all the records from the table. but I am not able to insert a new record in the database table. I am not getting any error/exception and it is running each statement cleanly but there is no effect in database below is my controller where I am using the repository and unitof work. Can somebody tell me where I am wron or what code/statements I have left in this code. I ahve checked it lot of time and I am stucked now. Not getting the problem

Controller:

 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();
        }

Repository class

 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;
            }
        }

UnitofWork Interface

  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;
        }
    }

My UnitofWork and Repository class derives from connection class where dbcontext is defined.

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

Is it that my dbContext is creating a new instance everytime like explained Here

and if yes then how can I resolve it.

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);

After this, you should see your object mapped by EF in local memory.

this._unitOfWork.Commit();

Here your object should be pushed to database. dbContext.SaveChanges() return number of changed records which should be in your case 1.

Msg = "Employee Created Successfully";

Update: So the problem is in your Connection class as you suggested.

I would create your DbContext in one place and then pass it to repository and unit of work. You could also create DbContext in unit of work constructor and then pass UOW to repository. This is one of my older implementation of this:

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);
    }       
}

Please find answer in below link for more details

Crud Operation with UnitOfWork

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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