在实体框架中使用通用存储库和UnitofWork模式进行详细的CRUD操作

时间:2019-05-30 07:25:51

标签: asp.net-mvc entity-framework-6 repository-pattern master-detail unit-of-work

我必须创建在多个表中插入数据的主Detail Crud,我正在使用UnitOfWork和通用的Repository模式。

我从数据库中获取具有关联关系的记录,也成功保存了记录,但是更新时出现了问题

我的UnitOfWork

public class UnitOfWorks : IDisposable, IUnitOfWorks
{
    #region Private member variable

    //private readonly EERPEntities1 _context = null;
    private readonly EERPEntities2 _context = null;
    private GenericRepository<Yarn_Colors> _Yarn_Colors_vmRepository;
    //private GenericRepository<GetFellows_Result> _storeProcedureRepository;
    private GenericRepository<Yarn_Blends> _yarnBlendRepository;
    private GenericRepository<Yarn> _yarnRepository;
    private GenericRepository<Yarn_CountClasses> _yarnCountClassesRepository;
    private GenericRepository<Yarn_Types> _yarnTypesRepository;
    private GenericRepository<Yarn_Brands> _yarnBrandsRepository;
    private GenericRepository<Yarn_Markings> _yarnMarkingRepository;
    private GenericRepository<Yarn_Sources> _yarnSourcesRepository;
    private GenericRepository<Fellow> _fellowRepository;
    private GenericRepository<Fellow_Branch> _fellowBranchRepository;
    private GenericRepository<Fellow_Characters> _fellowCharacterRepository;
    private GenericRepository<Fellow_Commission> _fellowCommisionRepository;
    private GenericRepository<Fellow_License> _fellowLicenseRepository;
    private GenericRepository<Fellow> _dropdownSupplierRepository;
    private GenericRepository<Character> _characterRepository;

    #endregion

    public UnitOfWorks()
    {
        //_context = new EERPEntities1();
        _context = new EERPEntities2();
    }

    #region Public Repository Creation properties...
    /// <summary>
    /// Get/Set Property for YarnColor repository.
    /// </summary>

    //public GenericRepository<GetFellows_Result> storeProcedureRepository
    //{
    //    get
    //    {
    //        if (this._storeProcedureRepository == null)
    //            this._storeProcedureRepository = new GenericRepository<GetFellows_Result>(_context);
    //        return _storeProcedureRepository;
    //    }
    //}
    public GenericRepository<Yarn> Yarn_Repository
    {
        get
        {
            if (this._yarnRepository == null)
                this._yarnRepository = new GenericRepository<Yarn>(_context);
            return _yarnRepository;
        }
    }

    public GenericRepository<Yarn_Colors> Yarn_Colors_vmRepository
    {
        get
        {
            if (this._Yarn_Colors_vmRepository == null)
                this._Yarn_Colors_vmRepository = new GenericRepository<Yarn_Colors>(_context);
            return _Yarn_Colors_vmRepository;
        }
    }

    public GenericRepository<Yarn_Blends> Yarn_Blend_Repository
    {
        get
        {
            if (this._yarnBlendRepository == null)
                this._yarnBlendRepository = new GenericRepository<Yarn_Blends>(_context);
            return _yarnBlendRepository;
        }
    }

    public GenericRepository<Yarn_CountClasses> Yarn_CountClasses_Repository
    {
        get
        {
            if (this._yarnCountClassesRepository == null)
                this._yarnCountClassesRepository = new GenericRepository<Yarn_CountClasses>(_context);
            return _yarnCountClassesRepository;
        }
    }

    public GenericRepository<Yarn_Types> Yarn_Types
    {
        get
        {
            if (this._yarnTypesRepository == null)
                this._yarnTypesRepository = new GenericRepository<Yarn_Types>(_context);
            return _yarnTypesRepository;
        }
    }

    public GenericRepository<Yarn_Brands> Yarn_BrandRepository
    {
        get
        {
            if (this._yarnBrandsRepository == null)
                this._yarnBrandsRepository = new GenericRepository<Yarn_Brands>(_context);
            return _yarnBrandsRepository;
        }
    }

    public GenericRepository<Yarn_Sources> YarnSources_Repository
    {
        get
        {
            if (this._yarnSourcesRepository == null)
                this._yarnSourcesRepository = new GenericRepository<Yarn_Sources>(_context);
            return _yarnSourcesRepository;
        }
    }

    public GenericRepository<Yarn_Markings> Yarn_MarkingsRepository
    {
        get
        {
            if (this._yarnMarkingRepository == null)
                this._yarnMarkingRepository = new GenericRepository<Yarn_Markings>(_context);
            return _yarnMarkingRepository;
        }
    }

    /// <summary>
    /// Get/Set Property for Fellow repository.
    /// </summary>
    public GenericRepository<Fellow> fellowRepository
    {
        get
        {
            if (this._fellowRepository == null)
                this._fellowRepository = new GenericRepository<Fellow>(_context);
            return _fellowRepository;
        }
    }

    public GenericRepository<Fellow_Branch> fellowBranchRepository
    {
        get
        {
            if (this._fellowBranchRepository == null)
                this._fellowBranchRepository = new GenericRepository<Fellow_Branch>(_context);
            return _fellowBranchRepository;
        }
    }

    public GenericRepository<Fellow_Characters> fellowCharacterRepository
    {
        get
        {
            if (this._fellowCharacterRepository == null)
                this._fellowCharacterRepository = new GenericRepository<Fellow_Characters>(_context);
            return _fellowCharacterRepository;
        }
    }

    public GenericRepository<Fellow_Commission> fellowCommisionRepository
    {
        get
        {
            if (this._fellowCommisionRepository == null)
                this._fellowCommisionRepository = new GenericRepository<Fellow_Commission>(_context);
            return _fellowCommisionRepository;
        }
    }

    public GenericRepository<Fellow_License> fellowLicenseRepository
    {
        get
        {
            if (this._fellowLicenseRepository == null)
                this._fellowLicenseRepository = new GenericRepository<Fellow_License>(_context);
            return _fellowLicenseRepository;
        }
    }

    public GenericRepository<Character> Character_Repository
    {
        get
        {
            if (this._characterRepository == null)
                this._characterRepository = new GenericRepository<Character>(_context);
            return _characterRepository;
        }
    }

    public GenericRepository<Fellow> DropDownSupplier_Repository
    {
        get
        {
            if (this._dropdownSupplierRepository == null)
                this._dropdownSupplierRepository = new GenericRepository<Fellow>(_context);
            return _dropdownSupplierRepository;
        }
    }

    /// <summary>
    /// List all .
    /// </summary>
    #endregion


    #region Implementing IDiosposable...

    #region private dispose variable declaration...
    private bool disposed = false;
    #endregion
    #region Public member methods...
    /// <summary>
    /// Save method.
    /// </summary>
    public void Save()
    {
        try
        {
            _context.SaveChanges();
        }
        //catch (DbEntityValidationException e)
        //{

        //    var outputLines = new List<string>();
        //    foreach (var eve in e.EntityValidationErrors)
        //    {
        //        outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
        //        foreach (var ve in eve.ValidationErrors)
        //        {
        //            outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
        //        }
        //    }
        //    System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

        //    throw e;
        //}
    catch (DbEntityValidationException ex)
    {
        // Retrieve the error messages as a list of strings.
        var errorMessages = ex.EntityValidationErrors
                .SelectMany(x => x.ValidationErrors)
                .Select(x => x.ErrorMessage);

        // Join the list to a single string.
        var fullErrorMessage = string.Join(";", errorMessages);

        // Combine the original exception message with the new one.
        var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

        // Throw a new DbEntityValidationException with the improved exception message.
        throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
    }
    }
    #endregion

    /// <summary>
    /// Protected Virtual Dispose method
    /// </summary>
    /// <param name="disposing"></param>
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                Debug.WriteLine("UnitOfWork is being disposed");
                _context.Dispose();
            }
        }
        this.disposed = true;
    }

    /// <summary>
    /// Dispose method
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion
}
}

我的通用存储库:

public class GenericRepository<TEntity> where TEntity : class
{
        #region Private member variables...
        //internal EERPEntities1 Context;
         internal EERPEntities2 Context;
         internal DbSet<TEntity> DbSet;
        #endregion

    #region Public Constructor...
    /// <summary>
    /// Public Constructor,initializes privately declared local variables.
    /// </summary>
    /// <param name="context"></param>
    public GenericRepository(EERPEntities2 context)
    {
        this.Context = context;
        this.DbSet = context.Set<TEntity>();
    }
    #endregion

    #region Public member methods...

    /// <summary>
    /// generic Get method for Entities
    /// </summary>
    /// <returns></returns>
    public virtual IEnumerable<TEntity> Get()
    {
        IQueryable<TEntity> query = DbSet;
        return query.ToList();
    }

    /// <summary>
    /// Generic get method on the basis of id for Entities.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public virtual TEntity GetByID(object id)
    {
        return DbSet.Find(id);
    }

    /// <summary>
    /// generic Insert method for the entities
    /// </summary>
    /// <param name="entity"></param>
    public virtual void Insert(TEntity entity)
    {
        DbSet.Add(entity);
    }

    /// <summary>
    /// Generic Delete method for the entities
    /// </summary>
    /// <param name="id"></param>
    public virtual void Delete(object id)
    {
        TEntity entityToDelete = DbSet.Find(id);
        Delete(entityToDelete);
    }

    /// <summary>
    /// Generic Delete method for the entities
    /// </summary>
    /// <param name="entityToDelete"></param>
    public virtual void Delete(TEntity entityToDelete)
    {
        if (Context.Entry(entityToDelete).State == EntityState.Detached)
        {
            DbSet.Attach(entityToDelete);
        }

        DbSet.Remove(entityToDelete);
    }

    /// <summary>
    /// Generic update method for the entities
    /// </summary>
    /// <param name="entityToUpdate"></param>
    public virtual void Update(TEntity entityToUpdate)
    {
        DbSet.Attach(entityToUpdate);
        Context.Entry(entityToUpdate).State = EntityState.Modified;
    }

    /// <summary>
    /// generic method to get many record on the basis of a condition.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public virtual IEnumerable<TEntity> GetMany(Func<TEntity, bool> where)
    {
        return DbSet.Where(where).ToList();
    }

    /// <summary>
    /// generic method to get many record on the basis of a condition but query able.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public virtual IQueryable<TEntity> GetManyQueryable(Func<TEntity, bool> where)
    {
        return DbSet.Where(where).AsQueryable();
    }

    /// <summary>
    /// generic get method , fetches data for the entities on the basis of condition.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public TEntity Get(Func<TEntity, Boolean> where)
    {
        return DbSet.Where(where).FirstOrDefault<TEntity>();
    }

    /// <summary>
    /// generic delete method , deletes data for the entities on the basis of condition.
    /// </summary>
    /// <param name="where"></param>
    /// <returns></returns>
    public void Delete(Func<TEntity, Boolean> where)
    {
        IQueryable<TEntity> objects = DbSet.Where<TEntity>(where).AsQueryable();
        foreach (TEntity obj in objects)
            DbSet.Remove(obj);
    }

    /// <summary>
    /// generic method to fetch all the records from db
    /// </summary>
    /// <returns></returns>
    public virtual IEnumerable<TEntity> GetAll()
    {
        return DbSet.ToList();
    }

    /// <summary>
    /// Inclue multiple
    /// </summary>
    /// <param name="predicate"></param>
    /// <param name="include"></param>
    /// <returns></returns>
    public IQueryable<TEntity> GetWithInclude(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate, params string[] include)
    {
        IQueryable<TEntity> query = this.DbSet;
        query = include.Aggregate(query, (current, inc) => current.Include(inc));
        return query.Where(predicate);
    }

    /// <summary>
    /// Generic method to check if entity exists
    /// </summary>
    /// <param name="primaryKey"></param>
    /// <returns></returns>
    public bool Exists(object primaryKey)
    {
        return DbSet.Find(primaryKey) != null;
    }

    /// <summary>
    /// Gets a single record by the specified criteria (usually the unique identifier)
    /// </summary>
    /// <param name="predicate">Criteria to match on</param>
    /// <returns>A single record that matches the specified criteria</returns>
    public TEntity GetSingle(Func<TEntity, bool> predicate)
    {
        return DbSet.Single<TEntity>(predicate);
    }

    /// <summary>
    /// The first record matching the specified criteria
    /// </summary>
    /// <param name="predicate">Criteria to match on</param>
    /// <returns>A single record containing the first record matching the specified criteria</returns>
    public TEntity GetFirst(Func<TEntity, bool> predicate)
    {
        return DbSet.First<TEntity>(predicate);
    }
    //******************************   Store Procedure Methods *************************************//
    ///<Summary>
    /// <summary>
    ///    Get Data from Database using a stored procedure without passing parameter
    /// </summary>
      public IEnumerable<TEntity> ExecuteQuery(string spQuery)
    {
        //using (Context = new EERPEntities1())
        using (Context = new EERPEntities2())
        {
            return Context.Database.SqlQuery<TEntity>(spQuery).ToList();
        }
    }
    ///</Summary>
    /// <summary>
    /// Get Data From Database
    /// <para>Use it to retrieve data from a stored procedure</para>
    /// </summary>

    public IEnumerable<TEntity> ExecuteQuery(string spQuery, string parameters)
    {
        //using (Context = new EERPEntities1())
        using (Context = new EERPEntities2())
        {
            return Context.Database.SqlQuery<TEntity>(spQuery, parameters).ToList();
        }
    }

    /// <summary>
    /// Get Single Data From Database
    /// <para>Use it to retrieve single row of data from a stored procedure</para>
    /// </summary>
    public TEntity ExecuteQuerySingle(string spQuery, string parameters)
    {
        //using (Context = new EERPEntities1())
        using (Context = new EERPEntities2())
        {
            return Context.Database.SqlQuery<TEntity>(spQuery, parameters).FirstOrDefault();
        }
    }

    public int Removefellow(int fellowId)
    {
        //using (var context = new EERPEntities1())
        using (var context = new EERPEntities2())
        {
            var fellow = (from l in context.Fellow_Branch
                          where l.FellowID == fellowId
                          select l).Single();
            //context.Entry(fellow)
            //    .Reference(l => l.FellowID.ToString())
            //    .Load();
            fellow.FellowID = Convert.ToInt64(null);

            context.SaveChanges();
            return fellowId;
        }
    }

    /// <summary>
    /// Insert/Update/Delete Data To Database
    /// <para>Use it when to Insert/Update/Delete data through a stored procedure</para>
    /// </summary>
    public int ExecuteComnmand(string spQuery, string parameters)
    {
        int result = 0;

        try
        {
            //using (Context = new EERPEntities1())
            using (Context = new EERPEntities2())
            {
                result = Context.Database.SqlQuery<int>(spQuery, parameters).FirstOrDefault();
            }
        }
        catch (Exception)
        {

            throw;
        }
        return result;
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                Context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion
}
}

这是我的更新服务方法:

public bool UpdateFellow(decimal fellowId,Fellow fellowEntity)
{
    var success = false;

    if (fellowEntity != null)
    {
        using (var scope = new TransactionScope())
        {
            var fellowClass = _unitOfWorks.fellowRepository.GetByID(fellowId);
            // var fellowBranch = _unitOfWorks.fellowBranchRepository.GetByID(fellowId);

            if (fellowClass != null)
            {
                fellowClass.FellowID = fellowEntity.FellowID;
                fellowClass.FellowName = fellowEntity.FellowName;
                fellowClass.Fellow_Invoice_Name = fellowEntity.Fellow_Invoice_Name;
                fellowClass.Fellow_ShortName = fellowEntity.Fellow_ShortName;
                fellowClass.Owner_Name = fellowEntity.Owner_Name;
                fellowClass.Owner_Mobile = fellowEntity.Owner_Mobile;
                fellowClass.Owner_Phone = fellowEntity.Owner_Phone;
                fellowClass.Contact1_Name = fellowEntity.Contact1_Name;
                fellowClass.Contact1_Mobile = fellowEntity.Contact1_Mobile;
                fellowClass.Contact1_Phone = fellowEntity.Contact1_Phone;
                fellowClass.Contact1_Designation = fellowEntity.Contact1_Designation;
                fellowClass.Contact2_Name = fellowEntity.Contact2_Name;
                fellowClass.Contact2_Phone = fellowEntity.Contact2_Phone;
                fellowClass.Contact2_Mobile = fellowEntity.Contact2_Mobile;
                fellowClass.Contact2_Designation = fellowEntity.Contact2_Designation;
                fellowClass.Opening_Amount = fellowEntity.Opening_Amount;
                fellowClass.Opening_DC = fellowEntity.Opening_DC;
                fellowClass.Opening_Date = fellowEntity.Opening_Date;
                fellowClass.AAF_ELevel = fellowEntity.AAF_ELevel;
                fellowClass.Fellow_Branch = fellowEntity.Fellow_Branch;
                fellowClass.Fellow_Characters = fellowEntity.Fellow_Characters;
                fellowClass.Fellow_License = fellowEntity.Fellow_License;
                fellowClass.PortalSignIns = fellowEntity.PortalSignIns;
                fellowClass.Yarn_Bids = fellowEntity.Yarn_Bids;
                fellowClass.Yarn_Brands = fellowEntity.Yarn_Brands;

                _unitOfWorks.fellowRepository.Update(fellowClass);
                _unitOfWorks.Save();

                scope.Complete();
                success = true;
            }
        }
    }

    return success;
}

这是我的主要课程

public partial class Fellow
{
    public Fellow()
    {
        this.AAF_ELevel = new HashSet<AAF_ELevel>();
        this.Fellow_Branch = new HashSet<Fellow_Branch>();
        this.Fellow_Characters = new HashSet<Fellow_Characters>();
        this.Fellow_Commission = new HashSet<Fellow_Commission>();
        this.Fellow_License = new HashSet<Fellow_License>();
        this.Inq_InquiryMain = new HashSet<Inq_InquiryMain>();
        this.PortalSignIns = new HashSet<PortalSignIn>();
        this.Yarn_Bids = new HashSet<Yarn_Bids>();
        this.Yarn_Brands = new HashSet<Yarn_Brands>();
    }

    public long FellowID { get; set; }
    public string FellowName { get; set; }
    public string Fellow_Invoice_Name { get; set; }
    public byte[] Fellow_ShortName { get; set; }
    public string Owner_Name { get; set; }
    public string Owner_Phone { get; set; }
    public string Owner_Mobile { get; set; }
    public string Contact1_Name { get; set; }
    public string Contact1_Phone { get; set; }
    public string Contact1_Mobile { get; set; }
    public string Contact1_Designation { get; set; }
    public string Contact2_Name { get; set; }
    public string Contact2_Phone { get; set; }
    public string Contact2_Mobile { get; set; }
    public string Contact2_Designation { get; set; }
    public Nullable<double> Opening_Amount { get; set; }
    public string Opening_DC { get; set; }
    public Nullable<System.DateTime> Opening_Date { get; set; }

    public virtual ICollection<AAF_ELevel> AAF_ELevel { get; set; }
    public virtual ICollection<Fellow_Branch> Fellow_Branch { get; set; }
    public virtual ICollection<Fellow_Characters> Fellow_Characters { get; set; }
    public virtual ICollection<Fellow_Commission> Fellow_Commission { get; set; }
    public virtual ICollection<Fellow_License> Fellow_License { get; set; }
    public virtual ICollection<Inq_InquiryMain> Inq_InquiryMain { get; set; }
    public virtual ICollection<PortalSignIn> PortalSignIns { get; set; }
    public virtual ICollection<Yarn_Bids> Yarn_Bids { get; set; }
    public virtual ICollection<Yarn_Brands> Yarn_Brands { get; set; }
}

当我更新记录时,不是创建记录而是创建新记录,而是创建新记录,以及如果用户删除唯一的孩子而不是父级并更新记录,那么子记录如何删除,以及用户删除时如何跟踪更改一条记录详细信息,编辑一条记录详细信息,并添加新的一条记录详细信息,我如何跟踪更改并将其发送到数据库,这是一个主从详细情况

0 个答案:

没有答案