简体   繁体   English

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

[英]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. 我正在使用Ninject for DI在带有unitofwork和通用存储库的mvc 4.0中进行粗操作。 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. 我没有收到任何错误/异常,它正在干净地运行每个语句,但是在数据库中没有任何作用,下面是我使用存储库和unitof工作的控制器。 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. 我的UnitofWork和Repository类从定义dbcontext的连接类派生。

 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 是我的dbContext每次都在创建一个新实例,就像这里解释的那样

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. 之后,您应该看到EF在本地内存中映射了您的对象。

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. dbContext.SaveChanges()返回更改的记录数,在您的情况下应该为1。

Msg = "Employee Created Successfully";

Update: So the problem is in your Connection class as you suggested. 更新:所以问题出在您建议的Connection类中。

I would create your DbContext in one place and then pass it to repository and unit of work. 我将在一个地方创建DbContext,然后将其传递到存储库和工作单元。 You could also create DbContext in unit of work constructor and then pass UOW to repository. 您还可以在工作构造器单元中创建DbContext,然后将UOW传递到存储库。 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 使用UnitOfWork进行粗体操作

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

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