Skip to content

Instantly share code, notes, and snippets.

@sslotsky
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sslotsky/4e42d26e2b06fff59adc to your computer and use it in GitHub Desktop.
Save sslotsky/4e42d26e2b06fff59adc to your computer and use it in GitHub Desktop.
public class ChatRoom
{
[Key]
public Guid ID { get; set; }
public virtual ICollection<Message> Messages { get; set; }
}
public static class ChatRoomExtensions
{
public IQueryable<ChatRoom> WithMessagesFromUser(this IQueryable<ChatRoom> queryable, Guid userID)
{
return queryable
.Include("Messages")
.Where(cr => cr.Messages.Select(m => m.UserID).Contains(userID));
}
public IQueryable<ChatRoom> ActiveSince(this IQueryable<ChatRoom> queryable, DateTime date)
{
return queryable
.Include("Messages")
.Where(cr => cr.Messages.Select(m => m.CreatedAt).Any(d => DateTime.Compare(d, date) >= 0));
}
public IQueryable<ChatRoom> RecentlyActive(this IQueryable<ChatRoom> queryable)
{
return queryable.ActiveSince(DateTime.Today.AddDays(-7));
}
}
public class ChatRoomService
{
public List<ChatRoom> GetActiveChatRoomsForUser(Guid userID)
{
List<ChatRoom> chatRooms;
using (var context = new ChatDbContext())
{
chatRooms = context.ChatRooms
.Include("Messages.User")
.RecentlyActive()
.WithMessagesFromUser(userID)
.ToList();
}
return chatRooms;
}
}
@sslotsky
Copy link
Author

Untested. Demonstrates the use of extension methods on IQueryable<T> in order to achieve a Linq equivalent of Rails scopes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment