在 LINQ 中使用强类型对象执行 JOIN
我有两个使用实体数据模型生成的对象。这些对象如下所示:
public class Song
{
public int ID { get; set; }
public string Title { get; set; }
public double Duration { get; set; }
}
public class AlbumSongLookup
{
public int ID { get; set; }
public int SongID { get; set; }
public int AlbumID { get; set; }
}
我需要使用 LINQ 获取专辑的 Song 对象。我有专辑ID。目前,我正在尝试:
int albumID = GetAlbumID();
var results = from lookup in context.AlbumSongLookups
where lookup.AlbumID=albumID
select lookup;
我知道我需要加入。但我不确定的是,如何使用此 LINQ 查询将结果获取为 Song 对象?
谢谢!
I have two objects that have been generated with an entity data model. The objects look like the following:
public class Song
{
public int ID { get; set; }
public string Title { get; set; }
public double Duration { get; set; }
}
public class AlbumSongLookup
{
public int ID { get; set; }
public int SongID { get; set; }
public int AlbumID { get; set; }
}
I need to get the Song objects for an Album using LINQ. I have the Album ID. Currently, I'm trying:
int albumID = GetAlbumID();
var results = from lookup in context.AlbumSongLookups
where lookup.AlbumID=albumID
select lookup;
I understand that I need to do a join. But what I'm not sure about is, how do I get the results to be Song objects with this LINQ query?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此查询返回您期望的结果吗?
我假设这里存在 context.Songs 。
Does this query return what you're expecting?
I'm assuming the existence of context.Songs here.
这不行吗?
does this not work?
您可以将“导航属性”添加到“歌曲”实体,这样您就可以直接访问特定专辑的相应歌曲。实体框架将为您完成繁重的工作。
在您的情况下,它返回一个查找集合,您需要做的是查找与它们对应的 Song 对象。这可以使用以下方法完成:
You could add a "Navigation Property" to your "Song" Entity, this way, you'll be able to directly access the corresponding Songs of a particular album. Entity framework will do the heavy lifting for you.
In your case, it returns a collection of lookups, what you need to do is look for the Song objects corresponding to them. this can be done using:
像这样的东西应该有效:
Something like this should work: