Question

I'm trying to find a way to detect spam in my SignalR chat application. Every time a user sends a messsage I would like to check the amount of messages sent by that user the last 5 seconds. I have a database with 2 tables: Message and User, where messages gets logged with a MessageDate and users with UserID. There is a Many-to-One relationship between the tables (1 user per message, several messages per user).

How can I write a query to check for messages sent by a specific user the last 5 seconds?

I have tried looking for a solution online but I'm new to queries and it's hard to get everything right (the join, the range of dates, using count property and getting data models right).

The closest I've gotten is something like :

var db = new MessageContext();
int messageCount = (from op in db.Message
              join pg in db.User on op.UserID equals pg.UserID
              where pg.UserID == op.UserID 
                    && (a.Start.Date >= DateTime.Now.AddSeconds(-5) 
                        && a.Start.Date <= DateTime.Now)
              select op)
             .Count();

Thanks in advance, any help appriciated!

Was it helpful?

Solution

Actually i don't see why you need a join at all, if you have a many to many Relationship you shouldn't need a join (you should have navigation properties) so the code should look like this:

var q = db.Users
   .Select(usr=>
   new
   {
       User = usr,
       LastMessages = usr.Messages
        .OrderByDescending(msg=>msg.Date)
        .Take(5)
   })
   .Where(usr=>usr.LastMessages.All(msg=>msg.UpdateDate >= 5 minutes from now)
// Here q contains all the users that have posted 5 messages or more in the last 5 minutes as well as those last messages.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top