【问题标题】:Why Guid is stored as string and not guid type in azure table storage?为什么 Guid 在 Azure 表存储中存储为字符串而不是 guid 类型?
【发布时间】:2019-06-13 06:53:29
【问题描述】:

我将 guid 存储在我的 azure 表存储中,但类型是 在 Azure 表存储门户中显示为字符串而不是 guid。

我正在使用带有 sas 令牌的 rest api 将实体存储在 azure table storage 中。

{
  public Guid id {get;set;}
  public string name {get;set;}
}

string sastoke = GetSasToken(); // no issues here
string url = config.table_storage_url + sastoken  // no issues here

// assuming i already have rowkey and partition key 
myClass entity = new myClass{id = Guid.NewGuid();name = "abcdef";}

var content = new StringContent(JsonConvert.SerializeObject(entity), Encoding.UTF8, "application/json");
// creating http client
using (HttpClient client = new HttpClient())
{
   client.DefaultRequestHeaders.Accept.Clear();
   client.DefaultRequestHeaders.Accept.Add(new 
          MediaTypeWithQualityHeaderValue("application/json"));
   HttpResponseMessage response = await client.PostAsync(url, content);
   return response;
 }

预期:id 的类型应该是 azure 表存储门户中的 guid。

实际:id 类型在 azure 表存储门户中显示字符串。

【问题讨论】:

  • 您没有为 Guid 指定 OData 类型。见here
  • 嗨@John,你能在上面的代码中举个例子吗?

标签: c# azure azure-table-storage


【解决方案1】:

当您使用 azure table storage rest api 插入数据时,按照doc

默认情况下,属性创建为 String 类型,除非您指定不同的类型。

如果要指定显式类型,格式应如下所示(doc here):

所以你需要在使用 rest api 时为该属性显式指定一个类型(如Edm.Guid)。另请注意,如果您使用的是 SDK,则不会出现此类问题。

这是一个简单的代码(也许有一些更好的方法来指定类型,但这里只是一个解释):

实体类:

public class MyClass
{

    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public string Name { get; set; }

    public Guid TestId { get; set; }
}

主要方法:

        static void Main(string[] args)
        {

            string url_with_sasToken = "https://xxx.table.core.windows.net/ttt?sasToken";

            MyClass entity = new MyClass
            {
                PartitionKey = "ivan2",
                RowKey = "y1",
                Name = "jack60",
                TestId = Guid.NewGuid()
            };


            //here, I add the odata type for Guid type
            string s = JsonConvert.SerializeObject(entity).Replace("}","");
            s += ",\"TestId@odata.type\"" + ":" + "\"Edm.Guid\"}";
            Console.WriteLine(s);

            var content = new StringContent(s, Encoding.UTF8, "application/json");

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new
          MediaTypeWithQualityHeaderValue("application/json"));
                var t2 = client.PostAsync(url_with_sasToken , content).GetAwaiter().GetResult();
                Console.WriteLine(t2.StatusCode);
            }

            Console.WriteLine("completed---");
            Console.ReadLine();
        }

然后签入 azure 门户:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2017-05-26
    • 2010-10-19
    相关资源
    最近更新 更多