Include only partial entity in EF6 Include

c# entity-framework-6 linq

Question

I have a model which includes Punches that can have Attachments that has properties for Id, Name as well as BinaryData.

If i do:

var result = context.PunchSet
   .Where(p => p.PunchType == punchType && p.Project.Id == projectId)
   .Include(c => c.Contractor)
   .Include(c => c.ClearedBy)
   .Include(c => c.CreatedBy)
   .Include(a => a.Attachments)

The query is slow as molassis since the attachments can be both many and large. In this case all I need is the Id and Name of the attachments. So I tried:

var result = context.PunchSet
    .Where(p => p.PunchType == punchType && p.Project.Id == projectId)
    .Include(c => c.Contractor)
    .Include(c => c.ClearedBy)
    .Include(c => c.CreatedBy)
    .Include(a => a.Attachments.Select(a2 => new Attachment() { Id=a2.Id, Name=a2.Name} );

But that ends up with this error:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

Have not idea what that means and I've been stuck for hours. How can I include a partial entitiy in the result? I.e. don't read the binary data.

1
1
9/7/2016 1:12:02 PM

Popular Answer

You can try to select all desired properties in a single query and then join them together in memory.

db.PunchSet
    .Include(x => x.Contractor)
    // ... other includes of complete objects
    // then select properties for partial include
    .Select(x => new { obj = x, att = x.Attachments.Select(a => new { a.Id, a.Name }) })
    // end of database query context
    .AsEnumerable()
    // join the results in memory
    .Select(x =>
    {
        x.obj.Attachments = x.att.Select(a => new Attachment() { Id = a.Id, Name = a.Name }).ToList();
        return x.obj;
    });
1
9/7/2016 1:39:00 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow