Initializing strongly typed objects in LINQ to Entities

Graham Conzett picture Graham Conzett · Sep 17, 2009 · Viewed 8.6k times · Source

I have a plain old CLR object which is essentially a wrapper for two entity framework objects, I'm doing this so I can pass this wrapper object to a strongly typed view in the MVC framework. My foo wrapper class is very simple:

public class FooWrapper
{
    public FooWrapper(Foo f, Bar b)
    {
        this.FooObject = f;
        this.BarObject = b;
    }

    public Foo FooObject { get; private set; }
    public Bar BarObject { get; private set; }
}

What I have so far for my ListFoosWithBars function is as follows:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);
    IEnumerable<FooWrapper> results = (from f in _entities.FooSet
                                       join b in tempBar on f.ID equals b.foos.ID
                                       select new FooWrapper(f, b));
    return results;
}

This doesn't work because evidently LINQ to Entities doesn't support parametrized initialization, an exception is thrown that says just that: "Only parameterless constructors and initializers are supported in LINQ to Entities." I was wondering if there is another way to achieve this same result?

Answer

Robban picture Robban · Sep 17, 2009

IF you add a parameterless constructor to your FooWrapper and then use object initialization instead, like so:

public IEnumerable<FooWrapper> ListFoosWithBars(int userID)
{
    IEnumerable<Bar> tempBar = ListBarsByUserID(userID);

    IEnumerable<FooWrapper> results = (
        from f in _entities.FooSet
        join b in tempBar on f.ID equals b.foos.ID
        select new FooWrapper()
        {
            FooObject = f, 
            BarObject = b
        });

    return results;
}