【问题标题】:Serialize user defined CLR object to Azure Storage Table将用户定义的 CLR 对象序列化到 Azure 存储表
【发布时间】:2013-08-24 16:39:11
【问题描述】:

如果我有一个用户定义的 CLR 对象,它们都继承自 TableEntity,例如这些 CLR:

public class Person : TableEntity
{
   public string FirstName { get; set; }
   public string Prefix { get; set; }
   public string LastName { get; set; }
   public string EmailAddress { get; set; }
   public Address Address { get; set; }
   public List<string> AList { get; set; }
   public List<Urls> ListUrls { get; set; }
}

public class Address : TableEntity
{
   public string Street { get; set; }
   public string Zipcode { get; set; }
   public string HouseNumber { get; set; }
   public string City { get; set; }
}

public class Urls : TableEntity
{
   public Uri Real { get; set; }
   public Uri Fake { get; set; }
}

注意:我知道属性和类必须用Protobuf-net 的属性进行修饰。但为了简单起见,我暂时忽略了这些。

我想使用Protobuf-net 将其转换为byte[] 并将其序列化到Windows Azure 存储并将其反序列化回这些CLR 对象。我怎样才能做到这一点?

我遵循this 教程,但我被byte[] 卡住了。我不知道怎么写一个byte[]到表中。

如果问题不明确,请告诉我,我会尝试澄清更多。

【问题讨论】:

    标签: c# serialization azure azure-storage protobuf-net


    【解决方案1】:

    带有 TableEntity 的 Azure 存储是一个完整的框架。我建议同时尝试两者都是有问题的。也许把这两件事分开。例如:

    public class Person { // note no base class
        //...
    }
    

    现在通过 MemoryStream 对其进行序列化以获取您的 byte[](maojg 确保使用 ToArray(),而不是 GetBuffer())。

    然后分别:

    public class PersonBlob : TableEntity {
        public byte[] Data {get;set;}
    }
    

    (您甚至可以在这里使用泛型来同时支持所有类型,但我不确定)。

    您还可以添加 ToPerson / FromPerson 实用程序方法以在两者之间进行切换。

    有什么用吗?

    【讨论】:

    • 看起来很棒!你说我什至可以使用泛型。你那是什么意思? public List&lt;string&gt; AList { get; set; } 不支持序列化吗?
    • @Quoter 我的意思是:公共类 EntityBlob-of-T : TableEntity { public byte[] Data {get;set;} }
    • 我正在尝试您的解决方案,并且 To.Array() 方法始终返回 0 字节。当我查看 Azure 表时,整个对象都被保存了,而不仅仅是数据字节 []。知道可能出了什么问题吗?
    • @Quoter a:0 字节表示没有数据 - 您是否将任何成员标记为 ProtoMember 等?
    • CLR 对象中有数据。一切都被填满了。是的,我将所有标记都标记为原始成员。我想我知道出了什么问题。我必须包括太多的衍生和接口。但不能添加这些类库项目的引用,因为它会导致来自 VS2013 或类似的“循环引用”消息。
    【解决方案2】:

    我通过创建 CLR 对象的精确副本并让它们从 TableEntity 继承以进行序列化来修复它。

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多