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

Gra*_*ett 11 linq linq-to-entities entity-framework 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; }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我的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;
}
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ban 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 输入相同的东西,你就赢了. (3认同)

Sam*_*les 12

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

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


Ral*_*sen 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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 我会非常小心这种方法,但你基本上是通过调用AsEnumerable来否定Entity框架的好处.一旦指定您有效地从FooSet表中提取所有记录,然后在内存中本地执行连接.只要考虑数千(或数百万)条记录时的性能影响. (8认同)