将值序列化为OData

时间:2014-04-28 16:13:43

标签: .net odata odatalib

是否有一个函数(可能在ODataLib 5.6.1中)将.NET基元类型序列化为OData URI格式(see

例如:

new DateTime(2000,12,12).ToODataString() //would return: datetime’2000-12-12T12:00′

2 个答案:

答案 0 :(得分:1)

这是我的临时实现,直到有人知道ODataLib中的函数。

static public string ToODataUriString(object value)
{
    if (value == null) return "null";
    switch (value.GetType().FullName)
    {
        case "System.Guid":
            return string.Format("guid'{0}'", (Guid)value);
        case "System.Decimal":
            return string.Format("{0}m", (decimal)value);
        case "System.Single":
            return string.Format("{0}f", ((Single)value).ToString("R"));
        case "System.Double":
            return string.Format("{0}d", ((double)value).ToString("R"));
        case "System.Boolean":
            return string.Format("{0}", (Boolean)value).ToLower();
        case "System.DateTime":
            {
                DateTime dvalue = (DateTime)value;
                string format;
                if (dvalue.Second==0 && dvalue.Millisecond==0)
                    format = "yyyy-MM-ddTHH:mm"; //datetime’yyyy-mm-ddThh:mm[:ss[.fffffff]]’
                else if (dvalue.Millisecond == 0)
                    format = "yyyy-MM-ddTHH:mm:ss"; //datetime’yyyy-mm-ddThh:mm[:ss[.fffffff]]’
                else
                    format = "yyyy-MM-ddTHH:mm:ss.fffffff"; //datetime’yyyy-mm-ddThh:mm[:ss.fffffff]]’
                return string.Format("datetime'{0}'", dvalue.ToString(format));
            }
        case "System.DateTimeOffset":
            return string.Format("datetimeoffset'{0}Z'", ((DateTimeOffset)value).ToString("s"));
        case "System.Int16":
        case "System.Int32":
        case "System.Byte":
            return value.ToString();
        case "System.Int64":
            return string.Format("{0}L", value);
        case "System.TimeSpan":
            return string.Format("time'{0}'", (TimeSpan)value);
        case "System.String":
            // TODO Need better quote handling for escaping, this is not correct
            return string.Format("'{0}'", value.ToString().Replace("'", "''"));
        default:
            // TODO Need better quote handling for escaping, this is not correct
            return string.Format("'{0}'", value.ToString().Replace("'", "''"));
    }
}

答案 1 :(得分:1)

使用静态类Microsoft.Data.OData.Query.ODataUriUtils, 您可以调用ConvertToUriLiteral将值序列化为uri literal。

public static string ConvertToUriLiteral(object value, ODataVersion version)
public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model)
public static string ConvertToUriLiteral(object value, ODataVersion version, IEdmModel model, ODataFormat format)

您可以调用ConvertFromUriLiteral进行反序列化。

public static object ConvertFromUriLiteral(string value, ODataVersion version)
public static object ConvertFromUriLiteral(string value, ODataVersion version, IEdmModel model, IEdmTypeReference typeReference)