在LINQ to Entities中初始化强类型对象 [英] Initializing strongly typed objects in LINQ to Entities
问题描述
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屋!