views:

217

answers:

2

I'm new to Linq to Entity stuff, so I don't know if what I'm doing is the best approach.

When I do a query like this it compiles, but throws an error that it doesn't recognize the method GetItemSummaries. Looking it up, this seems to be because it doesn't like a custom method inside the query.

return (from c in _entity.Category
                from i in c.Items
                orderby c.Id, i.Id descending
                select new CategoryDto
                {
                    Id = c.Id,
                    Name =  c.Name,
                    Items = GetItemSummaries(c)
                }).ToList();

private IEnumerable<ItemSummary> GetItemSummaries(CategoryDto c)
{
    return (from i in c.Items
            select new ItemSummary
             {
               // Assignment stuff
             }).ToList();
}

How would I combine this into a single query since I can't call a custom method?

I tried just replacing the method call with the actual query, but then that complains that ItemSummary isn't recognized instead of complaining that the method name isn't recognized. Is there any way to do this? (Or a better way?)

A: 

Try making the GetItemSummaries method an extension method on the Category class

private static IEnumerable<ItemSummary> GetItemSummaries(this Category c)

and then call it with

select new Category
            {
                Id = c.Id,
                Name =  c.Name,
                Items = c.GetItemSummaries()
            }).ToList();

Marc

marc_s
Sorry, this is just a learning application so my namings are kind of lazy. The Category I'm returning is a Dto object created from an entity object, I don't think I can make an extension method on the Dto class and have it do what I want.
Brandon
why not? you can put an extension method on any object - as long as your "Category" object contains all the information you need in the GetItemSummaries method - no problem.
marc_s
+2  A: 

You should be able to do the following:

    return (
            from c in _entity.Category
            orderby c.Id descending
            select new CategoryDto
            {
                Id = c.Id,
                Name =  c.Name,
                Items = (
                    from i in c.Items
                    order by i.Id descending
                    select new ItemSummary
                    {
                        // Assignment stuff
                    }
                )
            }).ToList();

It's just a matter of making sure that ItemSummary is public so that it's visible to the query.

If it's just a Dto though, you could use an anon type, eg:

                    from i in c.Items
                    order by i.Id descending
                    select new
                    {
                        Id = i.Id,
                        Name = i.Name
                    }

This creates a type with the 'Id' and 'Name' properties. All depends what your consuming code needs :)

Timothy Walters