6

我正在尝试了解 Azure 表存储如何工作以创建 facebook 样式的提要,但我一直坚持如何检索条目。

(我的问题与https://stackoverflow.com/questions/6843689/retrieve-multiple-type-of-entities-from-azure-table-storage几乎相同,但答案中的链接已损坏。)

这是我的预期方法:

  1. 为我的应用程序中的所有用户创建一个个人提要,其中可以包含不同类型的条目(通知、状态更新等)。我的想法是将它们存储在按每个用户的分区键分组的 Azure 表中。

  2. 检索同一分区键中的所有条目,并根据条目类型将其传递到不同的视图。

如何在保持其独特属性的同时查询相同基本类型的所有类型的表存储?

需要一个类型化的CloudTableQuery<TElement>实体,如果我指定EntryBase为通用参数,我不会获得特定于条目的属性 ( NotificationSpecificProperty, StatusUpdateSpecificProperty),反之亦然。

我的实体:

public class EntryBase : TableServiceEntity
{
    public EntryBase()
    {


    }
    public EntryBase(string partitionKey, string rowKey)
    {
        this.PartitionKey = partitionKey;
        this.RowKey = rowKey;
    }
}


public class NotificationEntry : EntryBase
{
    public string NotificationSpecificProperty { get; set; }
}

public class StatusUpdateEntry : EntryBase
{
    public string StatusUpdateSpecificProperty { get; set; }
}

我对提要的查询:

List<AbstractFeedEntry> entries = // how do I fetch all entries?

foreach (var item in entries)
{

    if(item.GetType() == typeof(NotificationEntry)){

        // handle notification

    }else if(item.GetType() == typeof(StatusUpdateEntry)){

        // handle status update

    }

}
4

4 回答 4

7

终于有官方方法了!:)

查看 Azure 存储团队博客的此链接中的 NoSQL 示例:

Windows Azure 存储客户端库 2.0 表深入了解

于 2012-11-13T12:48:57.190 回答
2

有几种方法可以解决这个问题,你如何做到这一点取决于你的个人喜好以及潜在的性能目标。

  • 创建一个代表所有查询类型的合并类。如果我有 StatusUpdateEntry 和 NotificationEntry,那么我只需将每个属性合并到一个类中。序列化程序将自动填写正确的属性并将其他属性保留为空(或默认值)。如果您还在实体上放置“类型”属性(在存储中计算或设置),则可以轻松打开该类型。因为我总是建议在应用程序中从表实体映射到您自己的类型,所以这也可以正常工作(该类仅用于 DTO)。

例子:

[DataServiceKey("PartitionKey", "RowKey")]
public class NoticeStatusUpdateEntry
{
    public string PartitionKey { get; set; }   
    public string RowKey { get; set; }
    public string NoticeProperty { get; set; }
    public string StatusUpdateProperty { get; set; }
    public string Type
    {
       get 
       {
           return String.IsNullOrEmpty(this.StatusUpdateProperty) ? "Notice" : "StatusUpate";
       }
    }
}
  • 覆盖序列化过程。您可以通过挂钩 ReadingEntity 事件自己执行此操作。它为您提供原始 XML,您可以根据需要选择序列化。Jai Haridas 和 Pablo Castro 提供了一些示例代码,用于在您不知道类型时读取实体(包括在下面),您可以调整它以读取您知道的特定类型。

这两种方法的缺点是,在某些情况下,您最终会提取比您需要的更多的数据。您需要权衡您真正想要查询一种类型与另一种类型的程度。请记住,您现在可以在表格存储中使用投影,这样还可以减少线格式大小,并且当您有更大的实体或许多要返回的实体时,可以真正加快速度。如果您只需要查询一种类型,我可能会使用 RowKey 或 PartitionKey 的一部分来指定类型,这样我就可以一次只查询一种类型(您可以使用属性,但是这对于查询目的不如 PK 或 RK 有效)。

编辑:正如 Lucifure 所指出的,另一个不错的选择是围绕它进行设计。使用多个表、并行查询等。当然,您需要权衡超时和错误处理的复杂性,但根据您的需要,它也是一个可行且通常也是不错的选择。

读取通用实体:

[DataServiceKey("PartitionKey", "RowKey")]   
public class GenericEntity   
{   
    public string PartitionKey { get; set; }   
    public string RowKey { get; set; } 

    Dictionary<string, object> properties = new Dictionary<string, object>();   

    internal object this[string key]   
    {   
        get   
        {   
            return this.properties[key];   
        }   

        set   
        {   
            this.properties[key] = value;   
        }   
    }   

    public override string ToString()   
    {   
        // TODO: append each property   
        return "";   
    }   
}   


    void TestGenericTable()   
    {   
        var ctx = CustomerDataContext.GetDataServiceContext();   
        ctx.IgnoreMissingProperties = true;   
        ctx.ReadingEntity += new EventHandler<ReadingWritingEntityEventArgs>(OnReadingEntity);   
        var customers = from o in ctx.CreateQuery<GenericTable>(CustomerDataContext.CustomersTableName) select o;   

        Console.WriteLine("Rows from '{0}'", CustomerDataContext.CustomersTableName);   
        foreach (GenericEntity entity in customers)   
        {   
            Console.WriteLine(entity.ToString());   
        }   
    }  

    // Credit goes to Pablo from ADO.NET Data Service team 
    public void OnReadingEntity(object sender, ReadingWritingEntityEventArgs args)   
    {   
        // TODO: Make these statics   
        XNamespace AtomNamespace = "http://www.w3.org/2005/Atom";   
        XNamespace AstoriaDataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices";   
        XNamespace AstoriaMetadataNamespace = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";   

        GenericEntity entity = args.Entity as GenericEntity;   
        if (entity == null)   
        {   
            return;   
        }   

        // read each property, type and value in the payload   
        var properties = args.Entity.GetType().GetProperties();   
        var q = from p in args.Data.Element(AtomNamespace + "content")   
                                .Element(AstoriaMetadataNamespace + "properties")   
                                .Elements()   
                where properties.All(pp => pp.Name != p.Name.LocalName)   
                select new   
                {   
                    Name = p.Name.LocalName,   
                    IsNull = string.Equals("true", p.Attribute(AstoriaMetadataNamespace + "null") == null ? null : p.Attribute(AstoriaMetadataNamespace + "null").Value, StringComparison.OrdinalIgnoreCase),   
                    TypeName = p.Attribute(AstoriaMetadataNamespace + "type") == null ? null : p.Attribute(AstoriaMetadataNamespace + "type").Value,   
                    p.Value   
                };   

        foreach (var dp in q)   
        {   
            entity[dp.Name] = GetTypedEdmValue(dp.TypeName, dp.Value, dp.IsNull);   
        }   
    }   


    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);   
        }   
    }
于 2012-05-22T15:03:52.870 回答
1

当然,另一种选择是每个表只有一个实体类型,并行查询表并合并按时间戳排序的结果。从长远来看,这可能被证明是在可扩展性和可维护性方面更谨慎的选择。

或者,您将需要使用“dunnry”概述的某种通用实体,其中不显式键入非常见数据,而是通过字典保存。

我编写了一个备用 Azure 表存储客户端 Lucifure Stash,它支持对 azure 表存储的额外抽象,包括持久化到字典/从字典持久化,如果这是您想要追求的方向,它可能适用于您的情况。

Lucifure Stash 支持 > 64K 的大型数据列、数组和列表、枚举、复合键、开箱即用的序列化、用户定义的变形、公共和私有属性和字段等。它可在http://www.lucifure.com 或通过 NuGet.com 免费供个人使用。

编辑:现在在CodePlex开源

于 2012-05-22T16:20:47.423 回答
0

使用DynamicTableEntity作为查询中的实体类型。它有一个您可以查找的属性字典。它可以返回任何实体类型。

于 2014-11-10T22:12:11.497 回答