是否存在从EDM / OData类型到CLR类型的映射器?

时间:2011-08-22 23:37:04

标签: serialization azure odata azure-table-storage

我正在编写一些针对Azure Table Storage REST API的代码。 API使用OData,通常由.net客户端处理。但是,我没有使用客户端,所以我需要找出生成/使用OData XML的另一种方法。我可以使用Syndication类来做ATOM的东西,但不能使用OData / EDM< - > CLR映射。

是否有人知道OData / EDM< - >类型映射器,和/或CLR对象到OData实体转换器?

谢谢, 埃里克

1 个答案:

答案 0 :(得分:4)

这是一些转换XML元素(来自OData feed)并将其转换为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;
}