azurecreatequery

How to query by partitionkey in Azure Table Storage?


I have the following TableServiceContext class for books, I want to query the table Books by the partitionKey, please ignore the fact that I'm using the partition key as the book name, this is just for my learning sakes

   public class BookDataServiceContext: TableServiceContext
        {

            public BookDataServiceContext(string baseAddress, StorageCredentials credentials)
                : base(baseAddress, credentials)
            {
            }

            public IQueryable<Book> Books
            {
                get
                {
                    return this.CreateQuery<Book>("Books");
                }
            }

            public void AddMessage(string name, int value)
            {
                this.AddObject("Books", new Book {PartitionKey=name, BookName = name, BookValue = value});
                this.SaveChanges();
            }

            public Book GetBookByPartitionKey(Guid partitionKey)
            {
                var qResult = this.CreateQuery<Book>("Books");
    This doesnt work ---->           // qResult = qResult.Where(e => (e.PartitionKey.CompareTo(partitionKey)==0));

            } 
}

I get a "Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Services.Client.DataServiceQuery'. An explicit conversion exists (are you missing a cast?)" on that last line.

Any help will be appreciated!


Solution

  • qResult is already assigned a type by the compiler. You're trying to re-assign it to a different type, but that isn't allowed.

    Try this

    var someOtherName = qResult.Where(e => (e.PartitionKey.CompareTo(partitionKey)==0));
    

    Edit: It looks like your Books property is the wrong type.

    public DataServiceQuery<Book> Books
    {
        get
        {
            return this.CreateQuery<Book>("Books");
        }
    }
    
    public Book GetBookByPartitionKey(string partitionKey)
    {
        var qResult = Books.Where(e => (e.PartitionKey.CompareTo(partitionKey)==0));
    }