2011-08-22 84 views
3

我正在寫一些針對Azure表存儲REST API的代碼。 API使用OData,通常由.net客戶端處理。但是,我沒有使用客戶端,所以我需要找出另一種生成/使用OData XML的方法。我可以使用Syndication類來完成ATOM的內容,但不能使用OData/EDM - > CLR映射。是否存在從EDM/OData類型到CLR類型的映射器?

是否有人知道OData/EDM < - >類型映射器和/或CLR對象到OData實體轉換器?

謝謝, 埃裏克

回答

4

下面是一些代碼,其將XML元素(從OData源)並將其轉換爲一個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

謝謝!順便說一句,我愛你的博客 –

相關問題