![](/img/trans.png)
[英]Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
[英]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
并将该变量传递到每个 Author 属性后在顶部执行一次。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
,因此请考虑放弃它。祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.