在LINQ to Entities中初始化强类型对象

时间:2009-09-17 17:42:13

标签: linq entity-framework linq-to-entities strong-typing

我有一个普通的旧CLR对象,它本质上是两个实体框架对象的包装器,我这样做,所以我可以将这个包装器对象传递给MVC框架中的强类型视图。我的foo包装类非常简单:

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

到目前为止,我的ListFoosWithBars函数的内容如下:

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

这不起作用,因为显然LINQ to Entities不支持参数化初始化,抛出的异常只是说:“LINQ to Entities中只支持无参数构造函数和初始值设定项。”我想知道是否有另一种方法来实现同样的结果?

5 个答案:

答案 0 :(得分:20)

如果您向FooWrapper添加无参数构造函数,然后使用对象初始化,如下所示:

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

答案 1 :(得分:12)

好的,但是如果你想要FooObject和BarObject只是读取怎么办?对我来说似乎有点倒退,他们否定了在对象上使用构造函数的能力。

我可以看到很多人破坏了良好的封装实践,以便在这种情况下利用对象初始化。

答案 2 :(得分:6)

为什么不使用.AsEnumerable()?这样,您就不需要创建无参数构造函数,这就是您想要的。

你的代码差不多好了。将其更改为:

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

我今天遇到了同样的问题。我有一个带有一个参数构造函数的类。这个构造函数填充了一个私有的readonly字段,该字段仅由一个属性返回,只有get而不是set。

答案 3 :(得分:3)

尝试不同的初始化:

public class FooWrapper
{
    public FooWrapper() { }

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


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

答案 4 :(得分:2)