Last active
August 29, 2015 14:27
-
-
Save sslotsky/4e42d26e2b06fff59adc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Untested. Demonstrates the use of extension methods on
IQueryable<T>
in order to achieve a Linq equivalent of Rails scopes.