Sri*_*vas 5 c# azure azure-storage azure-table-storage
将所有行从一个表复制到另一个表的最佳方法是什么?
我尝试下面的代码来获取表中的所有行:
TableServiceContext _dataContext;
public IEnumerable<T> GetAllEntities()
{
IQueryable<T> query = null;
try
{
query = _dataContext.CreateQuery<T>(_tableName);
}
catch (Exception ex)
{
}
return query.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
但它不会超过900左右的行.我有几十万行.
更新的代码:
public class TableRepository<T> : IRepository<T>
where T : TableEntity
{
protected readonly string _tableName;
protected readonly TableServiceContext _dataContext;
protected readonly CloudTable _tableReference;
public TableRepository(string tableName, CloudTableClient tableClient)
{
_tableName = tableName;
_dataContext = tableClient.GetTableServiceContext();
_tableReference = tableClient.GetTableReference(tableName);
_dataContext.ResolveType = ResolveEntityType;
_dataContext.MergeOption = System.Data.Services.Client.MergeOption.NoTracking;
}
public IEnumerable<T> GetAllEntities()
{
List<T> allEntities = new List<T>();
try
{
Microsoft.WindowsAzure.Storage.Table.TableContinuationToken tableContinuationToken = null;
do
{
var queryResponse = _tableReference.ExecuteQuerySegmented<T>(null, tableContinuationToken, null, null);
tableContinuationToken = queryResponse.ContinuationToken;
allEntities.AddRange(queryResponse.Results);
}
while (tableContinuationToken != null);
}
catch (Exception ex)
{
throw new DALException(_tableName,_dataContext.BaseUri.OriginalString, "An error occured while querying data", ex);
}
return allEntities;
}
Run Code Online (Sandbox Code Playgroud)
}
但有错误:
错误121'T'必须是具有公共无参数构造函数的非抽象类型,以便在泛型类型或方法'Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteQuerySegmented中将其用作参数'TElement'
你只获得900个结果的原因是因为你遇到了延续令牌.默认情况下,对表服务的单个请求将返回最多1000个实体.它可能少于1000个实体(甚至0)但从不超过1000个.如果有更多可用实体,则表服务返回一个continuation token应该用于获取下一组实体的实体.
因此,您的代码应查找延续令牌,并应继续获取实体,直到表服务返回时间令牌.请看下面的示例代码:
private IEnumerable<T> FetchAllEntities()
{
List<T> allEntities = new List<T>();
CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
CloudTable table = storageAccount.CreateCloudTableClient().GetTableReference("MyTable");
Microsoft.WindowsAzure.Storage.Table.TableContinuationToken tableContinuationToken = null;
do
{
var queryResponse = table.ExecuteQuerySegmented<T>(null, tableContinuationToken, null, null);
tableContinuationToken = queryResponse.ContinuationToken;
allEntities.AddRange(queryResponse.Results);
}
while (tableContinuationToken != null);
return allEntities;
}
Run Code Online (Sandbox Code Playgroud)
更新
对于您的错误,请尝试更改以下内容
public class TableRepository<T> : IRepository<T>
where T : TableEntity
Run Code Online (Sandbox Code Playgroud)
至
public class TableRepository<T> : IRepository<T>
where T : TableEntity, new()
Run Code Online (Sandbox Code Playgroud)
注意new()后加TableEntity.
| 归档时间: |
|
| 查看次数: |
5164 次 |
| 最近记录: |