0

Here is a foreach statement I'd like to express in Linq to Entities. It loops through child entities (attachments) of a parent entity (currentFactSheet) to see if an attachment exists with a particular FileName. How can I condense this procedural code into a Linq to Entites statement?

FactSheet currentFactSheet = mainWindow.GetCurrentFactSheet();

bool attachmentExists = false;
foreach (var thisAttachment in currentFactSheet.AttachmentsNav)
{
    if (thisAttachment.FileName == nameOfAttachedFile)
    {
        attachmentExists = true;
    }
}

This is a partial image showing FactSheet (left) and the Attachment entity associated via a navigation property named AttachmentsNav:

enter image description here

I want to query in memory entities to avoid a round trip to the database. I've found examples like this that search only the parent level. I've made many attempts, but they never bring up intellisense with the field names on my child entity (specifically Attachment.FileName).

Thanks in advance.

Community
  • 1
  • 1
DeveloperDan
  • 4,626
  • 9
  • 40
  • 65

1 Answers1

2

Try this:

bool attachmentExists = currentFactSheet.AttachmentsNav.Any(a => a.FileName == nameOfAttachedFile);
Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90