Код: Выделить всё
[b]No.[/b]
[b]Cliente[/b]
[b]Asunto[/b]
[b]Resumen del reporte[/b]
[b]Describa con más detalle el registro[/b]
[b]Fecha[/b]
[b]Estado[/b]
@ContadorId
Seleccione una opcion
@foreach (var cliente in Clientes)
{
@cliente.Nombre
}
Seleccione una opcion
@foreach (var asunto in Asuntos)
{
@asunto.Asuntos
}
@Registros.Fecha.ToString("dd/MM/yyyy")
Nuevo
ACEPTAR
@code {
private Registros Registros = new Registros
{
Nombre = string.Empty,
Asunto = string.Empty,
Cliente = string.Empty,
DescCorta = string.Empty,
Descripcion = string.Empty
};
private string? UserName;
private string? UserLastName;
private int ContadorId;
private List Clientes = new List();
private List Asuntos = new List();
private List UserRegistros = new List();
private ApplicationUser? currentUser;
protected override async Task OnInitializedAsync()
{
try
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var userPrincipal = authState.User;
if (userPrincipal.Identity?.IsAuthenticated == true)
{
currentUser = await usermanager.GetUserAsync(userPrincipal);
UserName = currentUser?.FirstName ?? userPrincipal.Identity.Name;
UserLastName = currentUser?.LastName;
}
Registros.Fecha = DateTime.Now;
ContadorId = IdDisplayContador();
// Crear instancias separadas del DbContext de forma correcta
await using var dbContext = DbContextFactory.CreateDbContext();
Clientes = await dbContext.Clientes.ToListAsync();
Asuntos = await dbContext.Asuntos.ToListAsync();
UserRegistros = await dbContext.Registros
.Where(r => r.Nombre == UserName + " " + UserLastName)
.ToListAsync();
}
catch (Exception ex)
{
// Handle exceptions (e.g., log the error)
Console.Error.WriteLine($"Error during initialization: {ex.Message}");
}
}
private async Task LoadClientesAsync()
{
try
{
await using var dbContext = DbContextFactory.CreateDbContext();
Clientes = await dbContext.Clientes.ToListAsync();
}
catch (Exception ex)
{
// Handle exceptions (e.g., log the error)
Console.Error.WriteLine($"Error loading clients: {ex.Message}");
}
}
private async Task LoadAsuntosAsync()
{
try
{
await using var dbContext = DbContextFactory.CreateDbContext();
Asuntos = await dbContext.Asuntos.ToListAsync();
}
catch (Exception ex)
{
// Handle exceptions (e.g., log the error)
Console.Error.WriteLine($"Error loading issues: {ex.Message}");
}
}
private async Task HandleValidSubmit()
{
try
{
// Asegurarse de que UserName y UserLastName estén asignados
if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(UserLastName))
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var userPrincipal = authState.User;
if (userPrincipal.Identity?.IsAuthenticated == true)
{
currentUser = await usermanager.GetUserAsync(userPrincipal);
UserName = currentUser?.FirstName ?? userPrincipal.Identity.Name;
UserLastName = currentUser?.LastName;
}
}
//debe insertar los datos que se llenaron en el formulario
Registros.Nombre = UserName + " " + UserLastName;
Registros.Estado = "Nuevo";
await using (var dbContext = DbContextFactory.CreateDbContext())
{
dbContext.Registros.Add(Registros);
await dbContext.SaveChangesAsync();
}
// Usar un nuevo contexto para recargar los registros
await using (var dbContext = DbContextFactory.CreateDbContext())
{
UserRegistros = await dbContext.Registros
.Where(r => r.Nombre == $"{UserName} {UserLastName}")
.ToListAsync();
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error saving record: {ex.Message}");
}
}
private int IdDisplayContador()
{
return ++ContadorId;
}
}
< /code>
Консоль Отправьте мне это исключение: < /strong> < /p>
Fail: microsoft.entityframeworkcore.query [10100]
Исключение произошло при итерации по результатам запроса для контекста. Вторая операция была начата в этом экземпляре контекста до завершения предыдущей операции. Обычно это вызвано различными потоками одновременно с использованием одного и того же экземпляра DBContext. Для получения дополнительной информации о том, как избежать проблем с потоком с DBContext, см. Microsoft.entityframeworkcore.query.internal.singlequeryingEnumerable1.AsyncEnumerator.MoveNextAsync() System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. at Microsoft.EntityFrameworkCore.Infrastructure.Internal.ConcurrencyDetector.EnterCriticalSection() at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable< /code> 1.asyncenumerator.movenextasync ()
ошибка во время инициализации: вторая операция была начата в этом экземпляре контекста до завершения предыдущей операции. Обычно это вызвано различными потоками одновременно с использованием одного и того же экземпляра DBContext. Для получения дополнительной информации о том, как избежать проблем с потоком с DBContext, см. Https://go.microsoft.com/fwlink/?linkid ... 3.образное. Я уже проверил таблицу, и модель и все выглядят хорошо.
Подробнее здесь: https://stackoverflow.com/questions/794 ... kcore10100