mardi 4 août 2015

Trying to map (AutoMapper) result of DataAccessor method causes "The ObjectContext instance has been disposed" error

This is the method that should get company types from data accessor. The result should be mapped (using AutoMapper). However, I get {"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection."} during mapping. Also when I debug and look into Watch section, I see that companyTypeData has DynmaicProxies instead of List<CompanyType> ({System.Data.Entity.DynamicProxies.CompanyType_3FC9CC368D973CAD3E480E71CC0925070C9DAA04B4D2FDEA1AE8E2018EA52EE4} NNN.BO.Entities.CompanyType ...

I believe that this is related to lazyloading in EntityFramework. But I am using the architecture that was not created by me and I am not expert of EF, so I am not sure how to fix it correctly.

Here is Bll method:

public class CompanyTypeBll
    {
        private readonly ICompanyTypeAccessor _companyTypeAccessor;            
        public CompanyTypeBll()
        {
            _companyTypeAccessor = new CompanyTypeAccessor();
        }        

        public List<CompanyTypeViewModel> GetTwoLevelCompanyTypeStructure()
        {
            List<CompanyType> companyTypeData = _companyTypeAccessor.GetByFilter(x => x.ParentTypeId == null).ToList();              

            return Mapper.Map<List<CompanyTypeViewModel>>(companyTypeData);
        }
    }

Here is definition of DataAccess method "GetByFilter":

 public virtual IEnumerable<T> GetByFilter(Expression<Func<T, bool>> filter)
        {
            using (NnnDbContext context = new NnnDbContext())
            {
                return IncludeRefObjects(context.Set<T>()).Where(filter).ToList();
            }
        }     

And this is definition of CompanyType object:

public class CompanyType : BaseEntity //BaseEntity has Id and CreationDate
    {
        public string Name { get; set; }    
        public Guid? ParentTypeId { get; set; }

        #region Navigation properties    
        public virtual CompanyType ParentType { get; set; }            
        public virtual List<CompanyType> CompanySubTypes { get; set; }    
        public virtual List<Company> Companies { get; set; }    
        #endregion
    }

The ViewModel to which I am trying to map:

public class CompanyTypeViewModel
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Guid? ParentTypeId { get; set; }
        public virtual List<CompanyTypeViewModel> CompanySubTypes { get; set; }
    }

Aucun commentaire:

Enregistrer un commentaire