简体   繁体   中英

DbGeography.PointFromText error Exception has been thrown by the target of an invocation

I am starting my first project using spacial data. Im using VS 2012 and SQL 2012 I have referenced System.Data.Entity and can use DbGeography in my code but when I try to create a point I get the above error and don't understand why

here is my code

var text = string.Format(CultureInfo.InvariantCulture.NumberFormat,
                "POINT({0} {1})", submitted.Long, submitted.Lat);
            // 4326 is most common coordinate system used by GPS/Maps
            try
            {
                var wkb = DbGeography.PointFromText(text, 4226);
            }
            catch (Exception exc)
            {
            }

the syntax that OP has used is correct, the actual issue that caused this error was the SRID, 4226 is not a known SRID, But you already knew this. because it is in your comment :)

A one line example of the correct usage in your scenario would be:

var wkb = DbGeography.PointFromText($"POINT({submitted.Long} {submitted.Lat})", 4326);

Where did you go wrong though? Whenever you get a

System.Reflection.TargetInvocationException

With a message of

Exception has been thrown by the target of an invocation

You must immediately check the Inner Exception for the details on the actual error, in this case it is outlined clearly for you:

24204: The spatial reference identifier (SRID) is not valid. The specified SRID must match one of the supported SRIDs displayed in the sys.spatial_reference_systems catalog view.

I realise that this is an old thread, but IMO this is an example of second most common .Net developer issue that people keep posting on SO. Please read through your full exception stack before pulling your hair out.

I'm just guessing, but I reckon NullReferenceException issues would be the most common :)

is wrong to order the lat and long

the correct is:

DbGeography.PointFromText(POINT(lat long), 4226);

Complete class:

public static DbGeography CreatePoint(double latitude, double longetude, int srid = 4326)
    {
        var lon = longetude.ToString(CultureInfo.InvariantCulture);
        var lat = latitude.ToString(CultureInfo.InvariantCulture);

        var geo = $"POINT({lat} {lon})";

        return DbGeography.PointFromText(geo, srid);
    }

Call:

CreatePoint(-46.55377, 23.11817)

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