为什么我的 Lambda 查询返回匿名类型而不是 Linq 的强类型返回值?
好吧,请耐心等待...直到几天前才完成任何 Linq 或 Lambda :)
我正在使用 C# 和 ADO.NET 实体框架。我想查询我的模型并根据关系返回对象列表。
这是我的代码:(
var query = db.Achievements.Join
(
db.AchievementOrganisations,
ach => ach.AchievementId,
ao => ao.AchievementId,
(ach, ao) => new { Achievement = ach }
);
var query2 = from s in db.Achievements
join h in db.AchievementOrganisations
on s.AchievementId equals h.AchievementId
select s;
对格式感到抱歉)
我的问题是为什么第一个查询(我认为是 Lambda 表达式)返回匿名类型:
{System.Data.Objects.ObjectQuery<<>f__AnonymousType1<MyApp.Models.Achievement>>}
...但第二个查询(LINQ 查询)我得到强类型值回:
{System.Data.Objects.ObjectQuery<MyApp.Models.Achievement>}
这是为什么呢?
干杯,
本
Ok, bear with me... hadn't done any Linq or Lambda until a couple of days ago :)
I'm using C# and the ADO.NET Entity Framework. I want to query my model and get back a List of objects based on a relationship.
Here's my code:
var query = db.Achievements.Join
(
db.AchievementOrganisations,
ach => ach.AchievementId,
ao => ao.AchievementId,
(ach, ao) => new { Achievement = ach }
);
var query2 = from s in db.Achievements
join h in db.AchievementOrganisations
on s.AchievementId equals h.AchievementId
select s;
(sorry about the formatting)
My question is why does the first query, which I believe is a Lambda Expression, return an Anonymous Type:
{System.Data.Objects.ObjectQuery<<>f__AnonymousType1<MyApp.Models.Achievement>>}
...but the second query (a LINQ query) I get a strongly-typed value back:
{System.Data.Objects.ObjectQuery<MyApp.Models.Achievement>}
Why is this?
Cheers,
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这一点是第一次调用中的问题:
您正在创建一个具有
Achievement
类型的Achievement
属性的新匿名类型。我怀疑您只是想要:
...虽然进行连接并忽略您要连接的表有点奇怪。
基本上,每当您看到
new { ... }
时,就意味着匿名类型。 (不要与使用推断元素类型构建数组的new[] { ... }
或new List{ ... }
等混淆这将使用给定的内容构建一个新的List
。This bit is the problem in the first call:
You're creating a new anonymous type with an
Achievement
property of typeAchievement
.I suspect you just want:
... although it's slightly odd to do a join and ignore the table you're joining with.
Basically, whenever you see
new { ... }
that means an anonymous type. (Not to be confused withnew[] { ... }
which builds an array with an inferred element type, ornew List<string> { ... }
etc which will build a newList<string>
with the given contents.