使用从 EF 查询获取的扩展属性将 EF 查询结果转换为扩展类型
我有一个 Tag 对象:
public class Tag
{
public int TagID { get; set; }
public string Name { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
public Tag()
{
Jobs = new HashSet<Job>();
}
}
和扩展:
public class RecentTag : Tag
{
public int Count { get; set; }
}
...并且我正在尝试检索最近标签对象的列表,其中包含添加到每个对象的查询中的计数:
public IEnumerable<RecentTag> GetRecentTags(int numberofdays)
{
var tags = Jobs
.Where(j => j.DatePosted > DateTime.Now.AddDays(-(numberofdays)))
.SelectMany(j => j.Tags)
.GroupBy(t => t, (k, g) => new
{
RecentTag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
// return RecentTags { TagID, Name, Count, Jobs }
}
那么,如何将查询结果转换为最近标签类型和返回扩展对象的列表?
任何帮助将不胜感激。提前致谢!
I've got a Tag object:
public class Tag
{
public int TagID { get; set; }
public string Name { get; set; }
public virtual ICollection<Job> Jobs { get; set; }
public Tag()
{
Jobs = new HashSet<Job>();
}
}
and extended:
public class RecentTag : Tag
{
public int Count { get; set; }
}
...and I'm trying to retrieve a list of RecentTag objects with Count from the query added to each object:
public IEnumerable<RecentTag> GetRecentTags(int numberofdays)
{
var tags = Jobs
.Where(j => j.DatePosted > DateTime.Now.AddDays(-(numberofdays)))
.SelectMany(j => j.Tags)
.GroupBy(t => t, (k, g) => new
{
RecentTag = k,
Count = g.Count()
})
.OrderByDescending(g => g.Count);
// return RecentTags { TagID, Name, Count, Jobs }
}
So, how do I cast results of the query to RecentTag type and return the list of extended objects?
Any help would be appreciated. Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果Jobs实际上是Tags的集合,并且它们实际上是RecentTag对象,那么您可以简单地使用Cast方法。
但是,如果 Jobs 不是标签的集合,那么您需要投影到最近标签对象中。
if Jobs is actually a collection of Tags, and they are in fact RecentTag objects, then you can simply use the Cast method.
However, if Jobs is not a collection of tags, then you need to project into a RecentTags objects..
我最终做了:
I ended up doing: