开发者

Load only a single associated entity

I have repository to manage operations on ComplaintTypes which has a large number of associated entities so I def. do NOT want to load everything, thus I have LazyLoadingEnabled = true;. I do however want to load one associated entity, for instance: ComplaintSubType

This is working for me, but I'm thinking there is a better way? Thanks!

namespace Complaint.Dal.Repositories
{
    public class ComplaintTypeRepository : RepositoryBase<ComplaintType>, IComplaintTypeRepository
    {
        #region ctor

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="objectContext"></param>
        public ComplaintTypeRepository(IObjectContext objectContext)
            : base(objectContext)
        {
            //Lazy Load so we don't get bloated data
            objectContext.LazyLoadingEnabled = true;
        }

        #endregion

        #region Implementation of IComplaintRepository

        public IEnumerable<ComplaintType> GetAllComplaintTypes()
        {
            //Load the related SubTypes
            var result = GetAll(t => t.PK_Type_Id);
            foreach (var complaintType in result)
            {
                complaintType.ComplaintSubType.Load();
            }
            return result;
        }

        pu开发者_如何学运维blic ComplaintType GetComplaintType(int typeId)
        {
            var result = GetSingle(t => t.PK_Type_Id == typeId);
            result.ComplaintSubType.Load();
            return result;
        }

        public void UpdateComplaintType(ComplaintType entity)
        {
            Attach(entity);
        }

        #endregion
    }
}

Updated:

public IEnumerable<T> GetAll<TKey, TType>(Expression<Func<T, TKey>> orderBy)  
{  
    var ret = ObjectSet;  
    //set Orderby  
    ret.OrderBy(orderBy);  
    return ret.ToList();  
}


You could implement something like this

RepositoryBase

public virtual IQueryable<TEntity> BuildQuery(IQueryable<TEntity> query)
{
    return query;
}

public IQueryable<TEntity> GetQuery()
{
    return BuildQuery(_objectSet);
}

public IEnumerable<T> GetAll<TKey, TType>(Expression<Func<T, TKey>> orderBy)  
{  
    var ret = GetQuery();  
    //set Orderby  
    ret.OrderBy(orderBy);  
    return ret.ToList();  
}

In ComplaintTypeRepository...

public override IQueryable<TEntity> BuildQuery(IQueryable<TEntity> query)
{
    return query.Include("ComplaintSubType");
}


With LazyLoadingEnabled set to true, you should no longer need to have to explicitly load ComplaintSubType directly; whenever something touches the property, EF should load it up for you. Alternatively, you could use the Include("ComplaintSubType") method to load it up at the same time as ComplaintType; this would be the best option here.

HTH.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜