LINQ to Entities: Initializing Strongly Typed Objects

entity-framework linq linq-to-entities strong-typing

Question

I've created a simple CLR object that serves as a wrapper for two entity framework objects so that I can send it to an MVC framework strongly typed view. This is how my foo wrapper class works:

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; }
}

I now have the following for my ListFoosWithBars function:

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 fails because, as it turns out, LINQ to Entities does not accept parameterized initialization; in fact, an error is raised that specifically states, "Only parameterless constructors and initializers are supported in LINQ to Entities." I was curious if there was another method to get the same outcome.

1
11
9/17/2009 5:42:12 PM

Accepted Answer

If you give your FooWrapper a parameterless constructor and want to utilize object initialization instead, do the following:

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;
}
20
9/5/2010 2:23:50 PM

Popular Answer

I understand, but what if you want FooObject and BarObject to be read-only? I find it a little strange that they make it impossible to utilize the object's constructor.

I can imagine a lot of people going against good encapsulation principles in this situation in order to use object initialization.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow