简体   繁体   中英

Azure table storage: How to get a single entity by a partition key only?

I am trying to get a single entity provided only with a partition key. My current code is returning me a List from IEnumerable, but it doesn't seem very efficient to have a list when in fact it is only a single entity, and I have to do a foreach through it. Is there a way to achieve with without a list/IEnumerable?

var entities = currentTable.ExecuteQuery(new TableQuery<ItemEntity>()).Where(e => e.PartitionKey.Equals(itemEntity.xId)).ToList();

If you want to get a specified entity, you should provide Partition key and row key together.

But if you want to get a random entity, you should use the methods provided by GvS.

The result of the query is always an IEnumerable.

If you expect only a single result you can use:

var result = currentTable.ExecuteQuery(new TableQuery<ItemEntity>()).Where(e => e.PartitionKey.Equals(itemEntity.xId)); 

// First element from the result. Will fail when there is no element
var entity1 = result.First();

// First element from the result. Will give null when no element is available.
var entity2 = result.FirstOrDefault();

// First element from the result. Will fail when there is no element, or more as one element
var entity3 = result.Single();

// First element from the result. Will give null when one element is available, or fail (Exeption) when more as one.
var entity4 = result.SingleOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM