将一个表中的所有行复制到另一个表的最佳方法是什么?
我尝试使用下面的代码来获取表中的所有行:
TableServiceContext _dataContext;
public IEnumerable<T> GetAllEntities()
{
IQueryable<T> query = null;
try
{
query = _dataContext.CreateQuery<T>(_tableName);
}
catch (Exception ex)
{
}
return query.ToArray();
}
但它获取的行数不会超过 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;
}
}
但有错误:
Error 121 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TElement' in the generic type or method 'Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteQuerySegmented
最佳答案
您只返回 900 个结果的原因是您遇到了延续 token 。默认情况下,对表服务的单个请求最多将返回 1000 个实体。它可能少于 1000 个实体(甚至 0 个),但绝不会超过 1000 个。如果有更多可用实体,则表服务会返回一个继续 token
,该 token 应用于获取下一组实体.
因此,您的代码应该查找继续 token ,并继续获取实体,直到表服务返回时间 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;
}
更新
对于您的错误,请尝试更改以下内容
public class TableRepository<T> : IRepository<T>
where T : TableEntity
至
public class TableRepository<T> : IRepository<T>
where T : TableEntity, new()
注意在TableEntity
之后添加了new()
。
关于c# - 将所有行复制到 Azure 表存储中的另一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18376087/