说,我定义了以下实体:
public class User : IdentityUser
{
public virtual string Name { get; set; }
public virtual string Surname { get; set; }
public virtual List<Entry> Entries { get; set; }
}
public class Entry
{
[Key]
public virtual int Id { get; set; }
public virtual string UserId { get; set; }
public virtual User User { get; set; }
public virtual long Timestamp { get; set; }
public virtual string Comment { get; set; }
}
我想找回
很明显,我可以自己转储Users和Entries表并组织数据,但这效率很低。有没有一种方法可以通过Entity Framework查询生成这样的结果?
答案 0 :(得分:2)
不幸的是,您不能过滤Include
表达式,因此您将不得不创建一个投影-如果没有那么多属性,就不会太繁琐。
var users = from user in context.Users
select new User {
Name = user.Name,
Surname = user.Surname,
Entries = user.Entries.Where(u => u.Timestamp > X && u.Timestamp < Y).ToList()
}
答案 1 :(得分:0)
尝试一下,就我在您的问题中所见,它应该可以正常工作
var users = context.Users
// exclue this where caluse if you want the user to be loaded anyway
.Where(c => c.Entries.Any(i => i.Timestamp >= X && i.Timestamp <= Y))
.Select(c => new
{
User = c,
Entries = c.Entries.Where(i => i.Timestamp >= X && i.Timestamp <= Y))
})
.FirstOrDefault();
答案 2 :(得分:-1)
您可以通过使用数据库上下文来实现。我假设您的数据库上下文正在使用紧急加载,因此您可以执行以下操作:
_yourDataBaseContext.Set<User>()
.Select(it=> new User
{
Name = it.Name,
Surname = it.Surname,
Entries = it.Entries.ToList().Where(e=> e.Timestamp > x && e.Timestamp <y)
})
.Include("Entries")
.ToList();
答案 3 :(得分:-1)
所有用户的列表
_dbContext.Users();
具有每个用户的条目列表(如果用户没有条目,则为空列表)
using System.Data.Entity;
_dbContext.Users().Include(x => x.Entries);
条目的时间戳介于X和Y之间
using System.Data.Entity;
_dbContext.Users().Where(x => x.Entries.Any(y => y.Timestamp >= X && i.Timestamp <= Y))
.Select(c => new
{
User = c,
Entries = c.Entries.Where(x => x.Timestamp >= X && x.Timestamp <= Y))
}).ToList();