The setup is pretty standard. Created a view and also the repository with the SQL Server connection string. Passed the repository the view model and on the view model’s constructor I call a collection from the repository. It was all working fine until I tried to do it asynchronously using the async/await combo but now I get the error “The context cannot be used while the model is being created” when calling the repository’s collection.
Old working code:
void FillPeopleList()
{
PeopleList = _repository.GetPeople();
}
New broken code:
async void FillPeopleList()
{
await Task.Run(()=>
{
PeopleList = _repository.GetPeople(); // Error
});
}
EF is not thread-safe.
You cannot use the same context on multiple threads.