joell
joell

Reputation: 426

Forcing Entity Framework to query database

I have a service and a webapplication using the same database, and common library for the database context. I'm disposing my database contexts, however when I manually insert a row on the database it is not shown in the webapp but works in the service.

By logging what Entity Framework does I noticed the following difference:

SERVICE - Completed in 8 ms with result: EFMySqlDataReader
WEBAPP  - Completed in 16 ms with result: CachingReader

So I suspect it has something to do with that the webapp uses the cached result instead of querying the database. Is there a way to force to query the database?

--

For completeness, it produces both the same query:

public static async Task<int> CountMailsInQueueAsync()
{
    using (var ctx = new GdprContext())
    {
        ctx.Database.Log = s => Log.Debug(s);

        // SELECT `GroupBy1`.`A1` AS `C1`
        // FROM
        //   (SELECT COUNT(1) AS `A1`
        //    FROM `tbl_email` AS `Extent1`
        //    WHERE (0 = (`Extent1`.`MailStatus`))
        //      OR (1 = (`Extent1`.`MailStatus`))) AS `GroupBy1`;

        return await ctx.Emails
            .Where(e => e.MailStatus == InfMailStatus.Ready || e.MailStatus == InfMailStatus.Processing)
            .CountAsync();
    }
}

// same connection string: 
// "server=localhost;user=dev;database=dev;port=3306;password=none;charset=utf8;Allow User Variables=True;Convert Zero Datetime=True;Allow Zero Datetime=True"
//
// using MySql.Data.Entity v6.9.9

Upvotes: 1

Views: 85

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205739

EF does not cache query results (the so called second level cache).

The name CachingReader indicates that the WEBAPP project is using EF Cache package. Find how it is setup in that project and read the package documentation how to ignore/force cache rebuild (there must be a Purge method or something like that).

Upvotes: 3

Related Questions