超出范围但它有效,索引超出范围。必须是非负数且小于集合的大小
Out of Range but it works, Index was out of range. Must be non-negative and less than the size of the collection
所以我通过其他线程试图弄清楚为什么当我最初调用示例数据信息时会出现此错误。我点击第一个按钮平滑,第二个按钮,平滑然后我点击样本数据,我得到这个错误。但是,它实际上在 MongoDB 中工作我将如何避免此错误,因为如果我事先创建了类别等,它并没有真正超出范围。我已经搜索了很多答案来做到这一点,但它们确实超出了我的范围。
at System.Collections.Generic.List`1.get_Item(Int32 index)
at SuggestionAppWithTimCoreyUI.Pages.SampleData.GenerateSampleData() in D:\dotNet\SuggestionAppWithTimCoreyAPP\SuggestionAppWithTimCoreyUI\Pages\SampleData.razor:line 53
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
// the code
@page "/SampleData"
@inject ICategoryData categoryData
@inject IStatusData statusData
@inject IUserData userData
@inject ISuggestionData suggestionData
<h3>Sample Data</h3>
@if (categoriesCreated)
{
<h4>Categories have been created</h4>
}
else
{
<button class="btn btn-primary" @onclick="CreateCategories">Create Categories </button>
}
@if (statusesCreated)
{
<h4>Statuses have been created</h4>
}
else
{
<button class="btn btn-info" @onclick="CreateStatuses">Create Statuses </button>
}
<button class="btn btn-dark" @onclick="GenerateSampleData">Sample Data</button>
@code {
private bool categoriesCreated = false;
private bool statusesCreated = false;
private async Task GenerateSampleData()
{
UserModel user = new()
{
FirstName = "Tim",
LastName = "Corey",
EmailAddress = "tim@test.com",
DisplayName = "Sample Tim Corey",
ObjectIdentifier = "abc-123"
};
await userData.CreateUser(user);
var foundUser = await userData.GetUserFromAuthentication("abc-123");
var categories = await categoryData.GetAllCategories();
var statuses = await statusData.GetAllStatuses();
HashSet<string> votes = new();
votes.Add("1");
votes.Add("2");
votes.Add("3");
SuggestionModel suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[0],
Suggestion = "Our First Suggestion",
Description = "This is a suggestion created by the sample data generation method."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[1],
Suggestion = "Our Second Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[0],
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[2],
Suggestion = "Our Third Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[1],
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[3],
Suggestion = "Our Fourth Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[2],
UserVotes = votes,
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
votes.Add("4");
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[4],
Suggestion = "Our Fifth Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[3],
UserVotes = votes,
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
}
private async Task CreateCategories()
{
var categories = await categoryData.GetAllCategories();
if (categories?.Count > 0)
{
return;
}
CategoryModel cat = new()
{
CategoryName = "Courses",
CategoryDescription = "Full paid courses."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "Dev Questions",
CategoryDescription = "Advice on being a developer."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "In-Depth Tutorial",
CategoryDescription = "A deep-dive video on how to use a topic."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "10-Minute Training",
CategoryDescription = "A quick \"How do I use this?\" video."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "Other",
CategoryDescription = "Not sure which category this fits in."
};
await categoryData.CreateCategory(cat);
categoriesCreated = true;
}
private async Task CreateStatuses()
{
var statuses = await statusData.GetAllStatuses();
if (statuses?.Count > 0)
{
return;
}
StatusModel stat = new()
{
StatusName = "Completed",
StatusDescription = "The suggestion was accepted and the corresponding item was created."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Watching",
StatusDescription = "The suggestion is interesting. We are watching to see how much interest there is in it."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Upcoming",
StatusDescription = "The suggestion was accepted and it will be released soon."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Dismissed",
StatusDescription = "The suggestion was not something that we are going to undertake."
};
await statusData.CreateStatuses(stat);
statusesCreated = true;
}
}
getallcategories()
private readonly IMemoryCache _cache;
private readonly IMongoCollection<CategoryModel> _cattegories;
private const string CacheName = "CategoryData";
public MongoCategoryData(IDbConnection db, IMemoryCache cache)
{
_cache = cache;
_cattegories = db.CategoryCollection;
}
public async Task<List<CategoryModel>> GetAllCategories()
{
var output = _cache.Get<List<CategoryModel>>(CacheName);
if (output == null)
{
var results = await _cattegories.FindAsync(_ => true);
output = results.ToList();
_cache.Set(CacheName, output, TimeSpan.FromDays(1));
}
return output;
}
正如评论中所述,您似乎没有从数据库中提取任何内容。目前尚不清楚您的查询是什么(大概是全部),但可能会检查您的连接字符串是否实际上指向您认为的实例。大概它正在连接到某物,因为它没有抛出,但它可能是某个本地虚拟实例。
自从您表示您是通过教程学习此内容后的一些其他想法:
- 当您从数据库中提取数据时,请添加一些完整性检查,以免您的状态出现同样的问题。
- 假设您的
BasicUserModel
在创建时分配了一个 id,您可能只想执行一次。不要为每个条目创建一个单独的作者,而是在拉出 foundUser
并将该变量传递给每个作者后在顶部执行一次 属性.
- 据我统计,您在整个页面中至少调用了 17 次数据库。查找批量插入语句并将新值列表传递给它以最大限度地减少负载和延迟。
- 首先,我建议您在 _cache 值上使用 TryGetValue,因为您可以改为使用以下内容:
public async Task<List<CategoryModel>> GetAllCategories()
if (_cache.TryGetValue<List<CategoryModel>>(CacheName, out var results))
return results;
output = (await _cattegories.FindAsync(_ => true)).ToList();
_cache.Set(CacheName, output, TimeSpan.FromDays(1));
return output;
}
- 如果您有可用于类别的默认值,您可以执行以下操作:
SuggestionModel suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[0] ?? "<your default value>", //If categories is null, use the default value instead
Suggestion = "Our First Suggestion",
Description = "This is a suggestion created by the sample data generation method."
};
- 最后,我没有看到你在使用
votes
做任何事情,所以考虑放弃它。
祝你好运!
at System.Collections.Generic.List`1.get_Item(Int32 index)
at SuggestionAppWithTimCoreyUI.Pages.SampleData.GenerateSampleData() in D:\dotNet\SuggestionAppWithTimCoreyAPP\SuggestionAppWithTimCoreyUI\Pages\SampleData.razor:line 53
at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
// the code
@page "/SampleData"
@inject ICategoryData categoryData
@inject IStatusData statusData
@inject IUserData userData
@inject ISuggestionData suggestionData
<h3>Sample Data</h3>
@if (categoriesCreated)
{
<h4>Categories have been created</h4>
}
else
{
<button class="btn btn-primary" @onclick="CreateCategories">Create Categories </button>
}
@if (statusesCreated)
{
<h4>Statuses have been created</h4>
}
else
{
<button class="btn btn-info" @onclick="CreateStatuses">Create Statuses </button>
}
<button class="btn btn-dark" @onclick="GenerateSampleData">Sample Data</button>
@code {
private bool categoriesCreated = false;
private bool statusesCreated = false;
private async Task GenerateSampleData()
{
UserModel user = new()
{
FirstName = "Tim",
LastName = "Corey",
EmailAddress = "tim@test.com",
DisplayName = "Sample Tim Corey",
ObjectIdentifier = "abc-123"
};
await userData.CreateUser(user);
var foundUser = await userData.GetUserFromAuthentication("abc-123");
var categories = await categoryData.GetAllCategories();
var statuses = await statusData.GetAllStatuses();
HashSet<string> votes = new();
votes.Add("1");
votes.Add("2");
votes.Add("3");
SuggestionModel suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[0],
Suggestion = "Our First Suggestion",
Description = "This is a suggestion created by the sample data generation method."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[1],
Suggestion = "Our Second Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[0],
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[2],
Suggestion = "Our Third Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[1],
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[3],
Suggestion = "Our Fourth Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[2],
UserVotes = votes,
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
votes.Add("4");
suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[4],
Suggestion = "Our Fifth Suggestion",
Description = "This is a suggestion created by the sample data generation method.",
SuggestionStatus = statuses[3],
UserVotes = votes,
OwnerNotes = "This is the note for the status."
};
await suggestionData.CreateSuggestion(suggestion);
}
private async Task CreateCategories()
{
var categories = await categoryData.GetAllCategories();
if (categories?.Count > 0)
{
return;
}
CategoryModel cat = new()
{
CategoryName = "Courses",
CategoryDescription = "Full paid courses."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "Dev Questions",
CategoryDescription = "Advice on being a developer."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "In-Depth Tutorial",
CategoryDescription = "A deep-dive video on how to use a topic."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "10-Minute Training",
CategoryDescription = "A quick \"How do I use this?\" video."
};
await categoryData.CreateCategory(cat);
cat = new()
{
CategoryName = "Other",
CategoryDescription = "Not sure which category this fits in."
};
await categoryData.CreateCategory(cat);
categoriesCreated = true;
}
private async Task CreateStatuses()
{
var statuses = await statusData.GetAllStatuses();
if (statuses?.Count > 0)
{
return;
}
StatusModel stat = new()
{
StatusName = "Completed",
StatusDescription = "The suggestion was accepted and the corresponding item was created."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Watching",
StatusDescription = "The suggestion is interesting. We are watching to see how much interest there is in it."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Upcoming",
StatusDescription = "The suggestion was accepted and it will be released soon."
};
await statusData.CreateStatuses(stat);
stat = new()
{
StatusName = "Dismissed",
StatusDescription = "The suggestion was not something that we are going to undertake."
};
await statusData.CreateStatuses(stat);
statusesCreated = true;
}
}
getallcategories()
private readonly IMemoryCache _cache;
private readonly IMongoCollection<CategoryModel> _cattegories;
private const string CacheName = "CategoryData";
public MongoCategoryData(IDbConnection db, IMemoryCache cache)
{
_cache = cache;
_cattegories = db.CategoryCollection;
}
public async Task<List<CategoryModel>> GetAllCategories()
{
var output = _cache.Get<List<CategoryModel>>(CacheName);
if (output == null)
{
var results = await _cattegories.FindAsync(_ => true);
output = results.ToList();
_cache.Set(CacheName, output, TimeSpan.FromDays(1));
}
return output;
}
正如评论中所述,您似乎没有从数据库中提取任何内容。目前尚不清楚您的查询是什么(大概是全部),但可能会检查您的连接字符串是否实际上指向您认为的实例。大概它正在连接到某物,因为它没有抛出,但它可能是某个本地虚拟实例。
自从您表示您是通过教程学习此内容后的一些其他想法:
- 当您从数据库中提取数据时,请添加一些完整性检查,以免您的状态出现同样的问题。
- 假设您的
BasicUserModel
在创建时分配了一个 id,您可能只想执行一次。不要为每个条目创建一个单独的作者,而是在拉出foundUser
并将该变量传递给每个作者后在顶部执行一次 属性. - 据我统计,您在整个页面中至少调用了 17 次数据库。查找批量插入语句并将新值列表传递给它以最大限度地减少负载和延迟。
- 首先,我建议您在 _cache 值上使用 TryGetValue,因为您可以改为使用以下内容:
public async Task<List<CategoryModel>> GetAllCategories()
if (_cache.TryGetValue<List<CategoryModel>>(CacheName, out var results))
return results;
output = (await _cattegories.FindAsync(_ => true)).ToList();
_cache.Set(CacheName, output, TimeSpan.FromDays(1));
return output;
}
- 如果您有可用于类别的默认值,您可以执行以下操作:
SuggestionModel suggestion = new()
{
Author = new BasicUserModel(foundUser),
Category = categories[0] ?? "<your default value>", //If categories is null, use the default value instead
Suggestion = "Our First Suggestion",
Description = "This is a suggestion created by the sample data generation method."
};
- 最后,我没有看到你在使用
votes
做任何事情,所以考虑放弃它。
祝你好运!