Home > OS >  How to create entity with a Point type in EF Core (with Sqlite and SpatiaLite package installed)
How to create entity with a Point type in EF Core (with Sqlite and SpatiaLite package installed)

Time:06-07

I use Sqlite with EF core 6, and I installed spatialite package. I read a documentation that says this fluent api code should do the job:

modelBuilder.Entity<City>().Property(c => c.Location)
    .HasSrid(4326);

But I don't know how to write the Location property's type, since there is no Point type that can be defined, And right clicking the Point type recommends no suitable 'using'.

This is the entity that I want to define:

public class City
{        
    public string Title { get; set; }
    public string Label { get; set; }
    public Point // right clicking recommends only: using System.Drawing and using Radzen.Blazor

}

In Sqlite and Ef core 6: How to specify a type for this Point property and if the HasSrid(4326) defines the column as a Point type?

CodePudding user response:

I installed this package:

Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite

Now the property is defined.

Edit: But this property type isn't supported in Sqlite so I had to convert it to a string. Now I want to write this Query but I don't know how:

var nearestCity = db.Cities
    .OrderBy(c => c.Location.Distance(currentLocation))
    .FirstOrDefault();

Since the property is now a string. In the docs there is:

geometry.Distance(g) 

But my question is how to write above query?

CodePudding user response:

Have another read through the general Spaital data in EF Core article and the SQLite-specific one.

In addition to installing the Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite package, you need to call UseNetTopologySuite when configuring your DbContext.

options.UseSqlite(
    connectionString,
    x => x.UseNetTopologySuite());

The Point type you're looking for is inside the NetTopologySuite.Geometries namespace.

Calling HasSrid(4326) indicates that you want to use the WGS 84 coordinate system--the one typically used in GPS.

  • Related