我对C#中的linq / lambda有疑问。 当前,我在“ GetUserServerAsync”方法上执行了foreach循环,这导致每个条目都要进行额外的数据库查询。
在第二种方法中,我试图避免第一种方法的查询垃圾邮件。该方法仅适用于一台服务器。我如何为列表中的所有服务器做到这一点?
public async Task<UserServer> GetUserServerAsync(string serverId, CancellationToken cancellationToken) {
return await this.Context.UserServer
.Where(s => s.ServerId == serverId)
.Include(u => u.User)
.FirstOrDefaultAsync(cancellationToken);
}
public async Task<List<UserServer>> GetUserServerAsync(IEnumerable<Server.Server> server, CancellationToken cancellationToken) {
var serverIds = server.Select(x => x.ServerId).ToList();
return await Context.UserServer
.Where(x => serverIds.Contains(x.ServerId))
.Include(u => u.User)
.ToListAsync(cancellationToken);
}
public class UserServer {
public string UserServerId { get; set; }
[Required]
[InverseProperty("User")]
public string UserId { get; set; }
public User User { get; set; }
[Required]
[InverseProperty("Server")]
public string ServerId { get; set; }
public Server.Server Server { get; set; }
}
谢谢。