在 LINQ 中初始化新对象时出现问题
此代码构建时没有问题,但在执行时失败:
var query =
_db.STEWARDSHIP
.OrderByDescending(r => r.VisitDate)
.Where(r => SiteId == null || r.SiteAssoc.Id == iSiteId)
.Where(r => r.MarkedForDeletion == false)
.Select(r => new SearchResults(r.Id,
r.SiteAssoc.Name,
r.VisitDate,
r.VisitTypeValAssoc.Description));
错误消息是:
LINQ to Entities 中仅支持无参数构造函数和初始值设定项。
我在这里做错了什么?我必须将信息传递给构造函数来构建 SearchResults 对象。有没有办法做到这一点,或者我是否必须将其分为两步,获取结果,然后迭代结果以创建新对象?
更新:
将选择更改为此可以修复问题:
.Select(r => new SearchResults(){Id = r.Id,
Name = r.SiteAssoc.Name,
VisitDate = r.VisitDate,
VisitType = r.VisitTypeValAssoc.Description});
This code builds without problems but fails when executed:
var query =
_db.STEWARDSHIP
.OrderByDescending(r => r.VisitDate)
.Where(r => SiteId == null || r.SiteAssoc.Id == iSiteId)
.Where(r => r.MarkedForDeletion == false)
.Select(r => new SearchResults(r.Id,
r.SiteAssoc.Name,
r.VisitDate,
r.VisitTypeValAssoc.Description));
The error message is:
Only parameterless constructors and initializers are supported in LINQ to Entities.
What am I doing wrong here? I must pass info to the constructor to build the SearchResults objects. Is there a way to do this or do I have to make this a 2-step thing where I get the results and then iterate over the results to create the new objects?
UPDATE:
Changing the select to this fixes the issue:
.Select(r => new SearchResults(){Id = r.Id,
Name = r.SiteAssoc.Name,
VisitDate = r.VisitDate,
VisitType = r.VisitTypeValAssoc.Description});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
请参阅这篇文章 显式构造实体类型 '### ' in query 是不允许的。
LINQ 不允许在 select 语句中显式构造对象。
See this post Explicit construction of entity type '###' in query is not allowed.
LINQ doesn't allow the explicit construction of objects within the select statements.