EntityFramework 5 and Projection / Lazy Loading. Please, need advice RRS feed

  • Question

  • Hello,

    I have the following EF 5.0 entities:

    public class Pack {
      public Int32 Id { get; set; }
      public virtual ICollection<File> Files { get; set; }
    } // Pack
    public class File {
      public Int32 Id { get; set; }
      public Byte[] Data { get; set; }
    } // File
    With a generic repository I need to get ONE pack and its files IDs but not the data.

    On my generic repository I have the following method:

    public T First<T>(Expression<Func<T, Boolean>> criteria) where T : class {
      return _context.Set<T>().FirstOrDefault(criteria);
    } // First
    I am getting the Pack and mapping to the PackDtoModel as follows:
    Pack pack = _repository.First<Pack>(x => x.Id == packId);
    PackDtoModel model = new PackDtoModel  {
      Id = pack.Id,
      FilesIds = pack.Files.Select(x => x.Id).ToList()
    Is this loading the File Data fields? I do not want that!

    Should I use a projection to avoid loading the Files data?

    If yes, how? The first method returns a T and not an IQueryable.

    I am using Configuration.LazyLoadingEnabled = true ...

    Please, I need advice on this.

    Thank You,


    Sunday, December 9, 2012 1:32 PM


  • Hi Miguel,

    Welcome to the MSDN forum.

    Since you are using lazy loading, the related entities are loaded automatically. Thus, yes, Data fields are loaded. First, I recommend you turn off lazy loading via this line: context.Configuration.LazyLoadingEnabled = false;

    Then, try to use this:

                    var query = First<Pack>(x => x.Id == 1);
                    var result = context.Entry(query).Collection(p => p.Files).Query().Select(p => p.Id);

    Have a nice day.

    Alexander Sun [MSFT]
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by MDMoura Tuesday, December 11, 2012 9:23 PM
    Tuesday, December 11, 2012 5:51 AM