开发者

Is there a mapper to/from EDM/OData types to CLR types?

I am writing some code against the Azure Table Storage REST API. The API uses OData, which is normally handled by the .net client. However, I am not using the client, so I need to figure out another way to generate/consume OData XML. I can use the Syndication classes to do the ATOM stuff, but not the OData/EDM <-> CLR mapping.

Is anyone aware of a OData/开发者_高级运维EDM <-> type mapper, and/or CLR object to OData entity converter?

Thanks, Erick


Here's some code that converts an XML element (from an OData feed) and converts it to an ExpandoObject.

private static object GetTypedEdmValue(string type, string value, bool isnull)
{
    if (isnull) return null;

    if (string.IsNullOrEmpty(type)) return value;

    switch (type)
    {
        case "Edm.String": return value;
        case "Edm.Byte": return Convert.ChangeType(value, typeof(byte));
        case "Edm.SByte": return Convert.ChangeType(value, typeof(sbyte));
        case "Edm.Int16": return Convert.ChangeType(value, typeof(short));
        case "Edm.Int32": return Convert.ChangeType(value, typeof(int));
        case "Edm.Int64": return Convert.ChangeType(value, typeof(long));
        case "Edm.Double": return Convert.ChangeType(value, typeof(double));
        case "Edm.Single": return Convert.ChangeType(value, typeof(float));
        case "Edm.Boolean": return Convert.ChangeType(value, typeof(bool));
        case "Edm.Decimal": return Convert.ChangeType(value, typeof(decimal));
        case "Edm.DateTime": return XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.RoundtripKind);
        case "Edm.Binary": return Convert.FromBase64String(value);
        case "Edm.Guid": return new Guid(value);

        default: throw new NotSupportedException("Not supported type " + type);
    }
}

private static ExpandoObject EntryToExpandoObject(XElement entry)
{
    XNamespace xmlnsm = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
                xmlns = "http://www.w3.org/2005/Atom";

    ExpandoObject entity = new ExpandoObject();
    var dic = (IDictionary<string, object>)entity;

    foreach (var property in entry.Element(xmlns + "content").Element(xmlnsm + "properties").Elements())
    {
        var name = property.Name.LocalName;
        var type = property.Attribute(xmlnsm + "type") != null ? property.Attribute(xmlnsm + "type").Value : "Edm.String";
        var isNull = property.Attribute(xmlnsm + "null") != null && string.Equals("true", property.Attribute(xmlnsm + "null").Value, StringComparison.OrdinalIgnoreCase);
        var value = property.Value;

        dic[name] = GetTypedEdmValue(type, value, isNull);
    }

    return entity;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜