【发布时间】:2015-03-11 11:12:33
【问题描述】:
为什么一种方法有效而另一种无效,当它们似乎都在做同样的事情时,即构建一个实体。那么我的问题是,有没有办法在 L2E 查询中构造实体,而不必只使用 Linq 或两者都使用?
这很好用...
var queryToList = (from ac in ctx.AuthorisationChecks
where wedNumbers.Contains(ac.WedNo)
orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate
select new AuthorisationCheck
{
Blah = ac.Blah
}).ToList();
model.AuthorisationChecks = queryToList.Select(x => new AuthorisationCheck
{
Blah = x.Blah
}).ToList();
但是,如果我改变...
var queryToList
到
model.AuthorisationChecks queryToList // Of type List<AuthorisationCheck>
我收到标题中的错误...
The entity or complex type 'Model.AuthorisationCheck' cannot be constructed in a LINQ to Entities query.
编辑: 在模型中它很简单,这里没什么特别的。
public List<AuthorisationCheck> AuthorisationChecks { get; set; }
EDIT2: 稍微整理了一下(效果很好)...
model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks
where wedNumbers.Contains(ac.WedNo)
orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate
select ac).ToList()
.Select(x => new AuthorisationCheck
{
Blah = x.Blah
}).ToList();
EDIT2:我的解决方案 我对匿名类型方法不满意,因此继续创建了一个简单模型,其中仅包含我需要在视图模型中使用的属性。
更改了 model.AuthorisationChecks 的类型
来自
List<AuthorisationCheck> // List of Entities
到
List<AuthorisationCheckModel> // List of models
它允许以下代码工作,并且无需分析它似乎比使用匿名类型快得多(当然我不会两次转换为列表!)。
model.AuthorisationChecks = (from ac in ctx.AuthorisationChecks
where wedNumbers.Contains(ac.WedNo)
orderby ac.WedNo, ac.ExpAuthDate, ac.ActAuthDate
select new AuthorisationCheckModel
{
Blah = x.Blah
}).ToList();
附:我曾经被一位同事(曾经在微软工作)警告过,以这种方式直接使用实体不是一个好主意,也许这是他考虑的原因之一,我也注意到了一些奇怪在其他情况下(主要是损坏)直接使用实体的行为。
【问题讨论】:
-
你必须写
model.AuthorisationChecks = -
顺便说一句,它更快,因为在您的第一个查询中,您首先选择所有列,然后仅将 1 分配给您的新对象,您的最后一个查询仅选择 1 列
标签: c# linq entity-framework linq-to-entities