Search code examples
linq-to-entitieswcf-ria-services

How to query associations in Linq to Entity framework in .NET Ria Services


I have just started with Linq and Linq to Entity Framewok. On top of that with the .NET Ria services. My problem is that I have 2 tables Folder and Item with a many to many relationsship using a third "connection" table FolderItem like this:
(source: InsomniacGeek.com)

In the .NET RIA Service domain service, I want to create a method that returns all Items for a given FolderID.

In T-SQL , that would something like this:

SELECT * FROM Item i
INNER JOIN FolderItem fi ON fi.ItemID = i.ID
WHERE fi.FolderID = 123

My Linq knowledge is limited, but I want to do something like this:

public IQueryable<Item> GetItems(int folderID)
{
  return this.Context.Items.Where(it => it.FolderItem.ID == folderID);
}

This is not the correct syntax, it gives this error:

Cannot convert lambda expression to type 'string' because it is not a delegate type

What is the correct way of doing this (with associations) ?

Can I user the .Include("FolderItem") somehow?

Please, method syntax only.

PS. Here's how it would look like using a Query Expression:

  public IQueryable<Item> GetItemsByFolderID(int folderID)
  {
    return from it in this.Context.Items
           from fi in it.FolderItem
           where fi.Folder.ID == folderID
           select it;
  }

The qeustion is, how would it look like using the Method Based Query Syntax?


Solution

  • Your GetItems looks fine to me. You could also do:

    public IQueryable<Item> GetItems(int folderID)
    {
        return this.Context.FolderItems
                           .Where(fi => fi.ID == folderID)
                           .Select(fi => fi.Items);
    }
    

    Both should return the same thing.