简体   繁体   中英

Simple example on how to use Npgsql spatial types

Using the assembly version Npgsql.3.1.0-alpha6

I have a table in Postgre with a Geometry field. Data is valid. Connection to the database works fine. PostGre verion 9.5

I made the following code (consider it as a pseudo code since was done using Oxygene that is similar to C#, I expect the answer for C#):

  var connectionString: String := 'Server=192.168.0.11;User id=postgres;Password=password;Database=db';
  var queryString: String := 'select wkb_geometry as geom from link';

  using connection: NpgsqlConnection := new NpgsqlConnection(connectionString) do begin
    var command: NpgsqlCommand  := new NpgsqlCommand(queryString, connection);
    try
      connection.Open();
      var reader: NpgsqlDataReader := command.ExecuteReader();

      while reader.Read() do begin
        Console.WriteLine(' {0} {1}', reader[0].GetType(), reader[0].ToString() );
      end;

  reader.Close();

  except
  on ex: Exception do begin
    Console.WriteLine(ex.Message);
  end;
  end;
  Console.ReadLine();
end;  

This code works and show me the ascii HEX representation of the binary data from the Geometry field.

I made a win32 software where I retrieved the EWKB from PostGIS and then parsed the Geometry field HEX data. This way I retrieved each of the data to export to another format.

Then I used the Microsoft ADO connection and it parses and retrieve the data with the proper GIS objects and coordinates ready to be used.

Eventually Npgsql is already doing it, but since I have not seen any example, I am not aware how I get the spatial data parsed.

Update 1

I totally misundertand how it works. When I cheked reader[0].GetType() I realized that Npgsql is already parsing and creating the proper object according the NpgsqlTypes.

That solves my question.

Npgsql has a variety of type mappings built-in, including PostgisGeometry . See (for example) src/Npgsql/NpgsqlTypes/PostgisTypes.cs for the class methods.


Otherwise, there are a variety of geometry output and geometry access functions. Eg

var queryString: String := 'select ST_AsText(wkb_geometry) as geom from link';

will return the geometry in a human-readable well-known text (WKT) . There are several formats or ways to get individual coordinates as double values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM