views:

23

answers:

1

I have a view model that needs to encapsulate a couple of many-to-many relationships.

I have my LINQ to Entites query that returns the appropriate list, but can't figure out how to return a list of objects.

I have a Foo table, and a Bar table. Bar has a FK to Foo.ID, and a Description string. I want to create a FooViewModel that has Foo.ID, as well as list of all the Bar.Descriptions.

  public class FooViewModel {
    public int ID {get; set; }
    public IEnumerable Descriptions { get; set; }
  }


  var all = from f in ctx.Foo.Include("Bar")
            select new FooViewModel
            {
              ID = f.ID,
              Descriptions = <insert magic here>
            };

What am I missing?

A: 

In Linq to Sql, Foo objects would have a property "Bar" (or "Bars" if it's one-to-many), so it would be just:

var all = from f in ctx.Foo
            select new FooViewModel 
            { 
              ID = f.ID, 
              Descriptions = f.Bars;
            }; 

I'm told it works the same way in Linq-to-Entity, with the proviso that while that property is automatically create in L2S, there's some explicit task you must do manually to have L2e create it.

James Curran
That's what I thought, but when I try that, I get an error:LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.String] ToList[String](System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
chris
Try it without the ToList() (remembering to add the ToList() when you try reading the Descriptions property)
James Curran
Just get rid of `ToList` and don't add it back *anywhere*.
Craig Stuntz
Changing the property to an IEnumerable<Bar>, the above edit works. Once again, I seem to be trying to over-complicate things for myself.
chris