.net-coreentity-framework-corepostgisgeography

How calculate distance between two points in EF Core and PostgreSql database


I am trying to calculate the distance of the user current point with another point in the database. I wrote the following code but I get function st_x(geography) does not exist error.

var pointsQueryable = _context.Points;
var points = pointsQueryable.Select(x => new PointViewModel
        {
            Id = x.Id,
            Title = x.Title,
            Address = x.Address,
            Description = x.Description,
            Longitude = x.Location.X,
            Latitude = x.Location.Y,
            Image = x.Image,
            DistanceFromUser = x.Location.Distance(new Point(filter.UserLongitude, filter.UserLatitude)),
            
        });

Of course, I have already enabled postgis for the database with CREATE EXTENSION postgis; command.


Solution

  • I tested the given scenario on a similar project with following code sample and it works:

    var firstPoint = new Point(10, 20);
    var fooPoint = await _fooRepository.FirstOrDefaultAsync(p=>p.Geom.Distance(firstPoint) > 5);
    var distance = fooPoint.Geom.Distance(firstPoint);
    

    But in my case the Geom field of the entity is defined as "Geometry". Can you provide your entity class also so the question is more clear.

    If NetTopologySuit is used on project the following configuration might help.

    var builder = new DbContextOptionsBuilder<FooDbContext>()
        .UseNpgsql(configuration.GetConnectionString("Default"), 
            opts => { opts.UseNetTopologySuite(); });