Error getting value from 'WellKnownValue' on 'System.Data.Entity.Spatial.DbGeography

早过忘川 提交于 2019-11-30 23:17:03

I found out (with .NET Reflector) that the DbGeography-Type can be instantiated by a default constructor (with no arguments) BUT this default constructor doesn't set some important private members (like _spatialProvider).

This results in a NullReferenceException when WellKnownValue-Getter is called during deserialization. So what I did is what many people before had to do (and I hoped didn't have to do) - I created a custom JsonConverter.

One speciality was, that I had to register it in BreezeWebApiConfig instead of the normal WebApiConfig:

public class MyBreezeConfig : Breeze.ContextProvider.BreezeConfig
{
    protected override JsonSerializerSettings CreateJsonSerializerSettings()
    {
        JsonSerializerSettings result = base.CreateJsonSerializerSettings();
        result.Converters.Add(new WebDbGeographyJsonConverter());
        return result;
    }
}

And the converter:

public class WebDbGeographyJsonConverter : JsonConverter {
    public override bool CanConvert(Type objectType) {
        return typeof(DbGeography).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
        var jObj = JObject.Load(reader);
        if (jObj != null) {

            var geography = jObj["Geography"];
            if (geography != null) {
                var wktText = geography["WellKnownText"].Value<string>();
                if (!string.IsNullOrEmpty(wktText)) {
                    var coordSysId = geography["CoordinateSystemId"].Value<int?>() ?? DbGeography.DefaultCoordinateSystemId;
                    return DbGeography.FromText(wktText, coordSysId);
                }
            }
        }
        return null;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }

    public override bool CanWrite {
        get {
            // use default implementation of Serialization
            return false;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!