1

是否有函数(可能在 ODataLib 5.6.1 中)将 .NET 原始类型序列化为 OData URI 格式(请参阅参考资料)

例如:

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

2 回答 2

2

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

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)
于 2014-04-29T09:17:24.410 回答
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("'", "''"));
    }
}
于 2014-04-28T17:46:12.890 回答