11

我有一个普通的旧 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 仅支持无参数的构造函数和初始化程序。” 我想知道是否有另一种方法可以达到同样的效果?

4

5 回答 5

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;
}
于 2009-09-17T17:46:56.460 回答
12

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

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

于 2010-12-06T05:43:53.487 回答
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;
}

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

于 2011-06-21T08:40:42.163 回答
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;
}
于 2009-09-17T17:49:32.690 回答
2

我发现这很有用,对于“Linq to Entites 仅支持无参数构造函数”有哪些可能的解决方法

于 2010-12-20T17:04:26.893 回答