Search code examples
asp.net-mvcentity-frameworkstored-proceduresgeolocationasp.net-core

Stored Procedure returns old data


I'm very confused. I'm using EF CORE. I'm hoping this has happened for others in older Entity Frameworks.

I'm having a problem whereby I am providing different postcodes which are converted into lat longs.

@gLat nvarchar(50),
@gLong nvarchar(50)

DECLARE @Location geography = geography::Point(@gLat, @gLong,4326) 

however the "Distance" field is returning the same distance.

cast(@Location.STDistance(Location) / 1609.344 AS float) AS 'Distance' 
--Always returns the same distance AS THE LAST QUERY when back in C#

eg) if the postcode XXXXXX0 is given, the returned distance is 1.5 if a new query is called with postcode YYYYYY1, the distance returned is still 1.5 .......

I wondered if at first it was because of the scope, but it is set to AddScope which means a new context is create for each request.

services.AddScoped<IRepository, Repository>();

Solution

  • I found a solution to my problem.

    It turns out that my service, in startup.cs, was AddSingleton.

    services.AddSingleton<IPersonService, PersonService>(); //Needs to be AddScoped
    services.AddSingleton<IPersonRepository, PersonRepository>(); //Also needs to be AddScoped
    

    This wouldn't have worked as singleton will only be created once and will be the same instance for every http request.

    What we need is a new instance for every http request.

    Also, make sure that the services' scope is the same as the repositories.

    For more information you can go to this page What is the difference between services.AddTransient, service.AddScope and service.AddSingleton methods in Asp.Net Core 1?

    Please make any amendments to this if it's not all correct!

    Hope this helps =)