0

I'm trying to create a stats page on my website that shows how many rows have been added to a specific table in the last X minutes.

This is the first thing I tried:

int games = db.GameLogs.Where(t => t.GameEnded > DateTime.Now - TimeSpan.FromMinutes(1)).Count();

I get this ugly error:

enter image description here

This is the second thing I tried:

var games = db.GameLogs.FromSqlRaw("select count(*) from mtgbattles.gamelogs  where gameended > now() - interval 1 minute");

I get the error:

InvalidOperationException: The required column 'Id' was not present in the results of a 'FromSql' operation.

The query works fine in MySQL Workbench.

1 Answer 1

1

Try moving date calculation out of request:

var dt = DateTime.Now.AddMinutes(-1); // maybe `DateTime.UtcNow`
int games = db.GameLogs
    .Where(t => t.GameEnded > dt)
    .Count();

As for FromSqlRaw - currently it has some limitations, including :

  • The SQL query must return data for all properties of the entity type.

So your select statement should include all fields for GameLogs to make FromSqlRaw work.

Sign up to request clarification or add additional context in comments.

3 Comments

In general it seems like putting functions in a fluent EF sql call always causes problems. This is the second time it's bitten me. Your suggestion works great, thanks.
@JohnShedletsky was glad to help. Also there is SqlServerDbFunctionsExtensions.DateDiffMinute but they should not work for MySQL I assume)
MS needs to reconsider their SQL Server licensing situation. I have to use dumpster SQL because MSSQL costs 15k/core. As a shareholder, I guess it's good. But it's not a way to hold onto the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.