3

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?

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164

2 Answers2

4

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.

Magnus Johansson
  • 28,010
  • 19
  • 106
  • 164
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
2

You can have the parent entity contain the child entities. There are 2 things you have to do to do this:

1) Update your domain query to include the folder items and items:

return from x in Context.FolderItems
                        .Include("FolderItem")
                        .Include("FolderItem.Item")
       where x.ID == folderID
       select x

2) Update the metadata file so that the RIA service knows to return the associations to the client:

[MetadataTypeAttribute(typeof(FolderMetadata))]
public partial class Folder
{
     internal sealed class FolderMetadata
     {
           ...
           [Include]
           public FolderItem FolderItem; 
     }
}
Gus
  • 649
  • 5
  • 14