2014-10-17 16 views
0

什麼是最簡單的修復方法?更改區域時DbGeography中的FormatException異常

當此代碼在澳大利亞運行(寫入時)它可以正常工作。

public static void CreatePointTest() 
{ 
    double lat = -33.613869; 
    double lon = 153.123456; 

    var text = string.Format("POINT({0} {1})", lon, lat); 
    // 4326 is most common coordinate system used by GPS/Maps 
    var ExceptionOnThisLine = DbGeography.PointFromText(text, 4326); 
} 

當我改變我的電腦「法語(法國)」的區域碼並運行它,我得到了return語句,似乎是數字格式有關的異常:

System.Reflection.TargetInvocationException was unhandled 
_HResult=-2146232828 _message=Exception has been thrown by the target of an invocation. HResult=-2146232828 IsTransient=false Message=Exception has been thrown by the target of an invocation. Source=mscorlib StackTrace: 
     at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) 
[snip...] 
     InnerException: System.FormatException 
     _HResult=-2146233033 
     _message=24141: A number is expected at position 16 of the input. The input has ,613869. 
     HResult=-2146233033 
     IsTransient=false 
     Message=24141: A number is expected at position 16 of the input. The input has ,613869. 
     Source=Microsoft.SqlServer.Types 
     StackTrace: 
      at Microsoft.SqlServer.Types.WellKnownTextReader.RecognizeDouble() 
      at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePointText(Boolean parseParentheses) 
      at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type) 
      at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid) 
      at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid) 
      at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid) 
      at Microsoft.SqlServer.Types.SqlGeography.STPointFromText(SqlChars pointTaggedText, Int32 srid) 
     InnerException: 

回答

1

更換你行

var text = string.Format("POINT({0} {1})", lon, lat); 

通過

var text = string.Format(System.Globalization.CultureInfo.InvariantCulture, "POINT({0} {1})", lon, lat); 

法文中使用,作爲小數運算符而不是.

+0

在此期間,我已經使用它,這是一個類似的想法。按照你的方式做什麼的好處? var text = string.Format(new System.Globalization.CultureInfo(「zh-CN」),「POINT({0} {1})」,lon,lat); – dylanT 2014-10-18 00:00:25

+0

按照定義它是獨立於文化的,如果你不想區域特定的設置應該使用。但說實話:我認爲它實際上與en-US完全相同。這只是形式上的中立。 – Fratyx 2014-10-18 00:34:52

+0

好的,我讀了一下。 InvariantCulture永遠不會改變。但是,如果在將來的某個時候en-US決定用逗號格式化,或者如果某人定製文化以使用逗號,那麼代碼會再次以我的方法破解,所以InvariantCulture在這種情況下是最佳選擇。 – dylanT 2014-10-20 01:20:14