在LINQ to Entities中初始化强类型对象 [英] Initializing strongly typed objects in LINQ to Entities

查看:209
本文介绍了在LINQ to Entities中初始化强类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

public Foo FooObject {get;私人集合}
public Bar BarObject {get;私人集合}
}

到目前为止,我的ListFoosWithBars功能如下: p>

  public IEnumerable< FooWrapper> ListFoosWithBars(int userID)
{
IEnumerable< Bar> tempBar = ListBarsByUserID(userID);
IEnumerable< FooWrapper>结果=(从f在_entities.FooSet
加入b在tempBar上f.ID等于b.foos.ID
选择新的FooWrapper(f,b));
返回结果;
}

这不起作用,因为LINQ to Entities显然不支持参数初始化抛出一个例外:仅在LINQ to Entities中支持无参数构造函数和初始值设置。我想知道是否有另一种方式来实现同样的结果?

解决方案

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

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

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

返回结果;
}


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?

解决方案

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

这篇关于在LINQ to Entities中初始化强类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆