Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Microsoft.EntityFrameworkCore.Database.SyncNotSupported #89

Open
hades200082 opened this issue Dec 19, 2024 · 0 comments
Open

Microsoft.EntityFrameworkCore.Database.SyncNotSupported #89

hades200082 opened this issue Dec 19, 2024 · 0 comments

Comments

@hades200082
Copy link

I'm using EF Core with provider Microsoft.EntityFrameworkCore.Cosmos via Aspire.Microsoft.EntityFrameworkCore.Cosmos.

public static class AddItem
{
    public record Request(string Title, string? Description = null, DateTime? DueBy = null);
    public record Response
    {
        public Response(TodoListItem item)
        {
            Id = item.Id;
            Title = item.Title;
            Description = item.Description;
            DueBy = item.DueBy;
        }

        public Guid Id { get; init; }
        public string Title { get; init; }
        public string? Description { get; init; }
        public DateTime? DueBy { get; init; }
    }

    public class Validator : AbstractValidator<Request>
    {
        public Validator()
        {
            RuleFor(x => x.Title).NotEmpty().MinimumLength(6);
            RuleFor(x => x.DueBy)
                .GreaterThanOrEqualTo(DateTime.UtcNow)
                .When(x => x.DueBy is not null);
        }
    }
    
    public class Endpoint : TodoListItemCarterModule
    {
        public override void AddRoutes(IEndpointRouteBuilder app)
        {
            app.MapPost("/", Handler)
                .Produces<Response>(StatusCodes.Status201Created)
                .ProducesValidationProblem()
                .AddEndpointFilter<IdempotentAPIEndpointFilter>();
        }
    }

    private static async Task<IResult> Handler(
        [FromServices]AppDbContext db, 
        [FromServices]IValidator<Request> validator,
        [FromServices]LinkGenerator linkGenerator,
        [FromServices]IFusionCache cache,
        HttpContext httpContext,
        [FromBody] Request request)
    {
        var validationResult = await validator.ValidateAsync(request);
        if(!validationResult.IsValid)
            return Results.ValidationProblem(validationResult.GetValidationProblems());

        var item = new TodoListItem
        {
            Title = request.Title,
            DueBy = request.DueBy,
            Description = request.Description
        };

        await db.TodoListItems.AddAsync(item);
        await db.SaveChangesAsync();

        await cache.ExpireAsync($"{nameof(TodoListItem)}_list");
        return Results.Created(linkGenerator.GetUriByAddress(httpContext, "/todo-items/{id}", new RouteValueDictionary(new {id = item.Id})), new Response(item));
    }
}

Error summary

When I hit this endpoint with a valid payload I get the following error:

An error was generated for warning 'Microsoft.EntityFrameworkCore.Database.SyncNotSupported': Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. This exception can be suppressed or logged by passing event ID 'CosmosEventId.SyncNotSupported' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.

Stack trace

System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Database.SyncNotSupported': Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. This exception can be suppressed or logged by passing event ID 'CosmosEventId.SyncNotSupported' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
   at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
   at Microsoft.EntityFrameworkCore.Cosmos.Diagnostics.Internal.CosmosLoggerExtensions.SyncNotSupported(IDiagnosticsLogger`1 diagnostics)
   at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.ExecuteSqlQuery(String containerId, PartitionKey partitionKeyValue, CosmosSqlQuery query)
   at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable`1.Enumerator.MoveNext()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)
   at IdempotentAPI.Core.Idempotency.GenerateRequestsDataHashMinimalApiAsync(IList`1 arguments, HttpRequest httpRequest)
   at IdempotentAPI.Core.Idempotency.PrepareMinimalApiIdempotencyAsync(HttpContext httpContext, IList`1 arguments)
   at IdempotentAPI.MinimalAPI.IdempotentAPIEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
   at IdempotentAPI.MinimalAPI.IdempotentAPIEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<ExecuteValueTaskOfObject>g__ExecuteAwaited|128_0(ValueTask`1 valueTask, HttpContext httpContext, JsonTypeInfo`1 jsonTypeInfo)
   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass101_2.<<HandleRequestBodyAndCompileRequestDelegateForJson>b__2>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Full ProblemDetails response:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.6.1",
  "title": "System.InvalidOperationException",
  "status": 500,
  "detail": "An error was generated for warning 'Microsoft.EntityFrameworkCore.Database.SyncNotSupported': Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. This exception can be suppressed or logged by passing event ID 'CosmosEventId.SyncNotSupported' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.",
  "exception": {
    "details": "System.InvalidOperationException: An error was generated for warning 'Microsoft.EntityFrameworkCore.Database.SyncNotSupported': Azure Cosmos DB does not support synchronous I/O. Make sure to use and correctly await only async methods when using Entity Framework Core to access Azure Cosmos DB. See https://aka.ms/ef-cosmos-nosync for more information. This exception can be suppressed or logged by passing event ID 'CosmosEventId.SyncNotSupported' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.\r\n   at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)\r\n   at Microsoft.EntityFrameworkCore.Cosmos.Diagnostics.Internal.CosmosLoggerExtensions.SyncNotSupported(IDiagnosticsLogger`1 diagnostics)\r\n   at Microsoft.EntityFrameworkCore.Cosmos.Storage.Internal.CosmosClientWrapper.ExecuteSqlQuery(String containerId, PartitionKey partitionKeyValue, CosmosSqlQuery query)\r\n   at Microsoft.EntityFrameworkCore.Cosmos.Query.Internal.CosmosShapedQueryCompilingExpressionVisitor.QueryingEnumerable`1.Enumerator.MoveNext()\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)\r\n   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value, Type type, JsonSerializerSettings settings)\r\n   at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)\r\n   at IdempotentAPI.Core.Idempotency.GenerateRequestsDataHashMinimalApiAsync(IList`1 arguments, HttpRequest httpRequest)\r\n   at IdempotentAPI.Core.Idempotency.PrepareMinimalApiIdempotencyAsync(HttpContext httpContext, IList`1 arguments)\r\n   at IdempotentAPI.MinimalAPI.IdempotentAPIEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)\r\n   at IdempotentAPI.MinimalAPI.IdempotentAPIEndpointFilter.InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)\r\n   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<ExecuteValueTaskOfObject>g__ExecuteAwaited|128_0(ValueTask`1 valueTask, HttpContext httpContext, JsonTypeInfo`1 jsonTypeInfo)\r\n   at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass101_2.<<HandleRequestBodyAndCompileRequestDelegateForJson>b__2>d.MoveNext()\r\n--- End of stack trace from previous location ---\r\n   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)",
    "headers": {
      "Accept": [
        "*/*"
      ],
      "Host": [
        "localhost:49763"
      ],
      "User-Agent": [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0"
      ],
      "Accept-Encoding": [
        "gzip, deflate, br, zstd"
      ],
      "Accept-Language": [
        "en-GB,en;q=0.9"
      ],
      "Content-Type": [
        "application/json"
      ],
      "Origin": [
        "https://localhost:7044"
      ],
      "Referer": [
        "https://localhost:7044/"
      ],
      "Content-Length": [
        "61"
      ],
      "sec-ch-ua-platform": [
        "\"Windows\""
      ],
      "sec-ch-ua": [
        "\"Microsoft Edge\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\""
      ],
      "DNT": [
        "1"
      ],
      "sec-ch-ua-mobile": [
        "?0"
      ],
      "sec-fetch-site": [
        "same-site"
      ],
      "sec-fetch-mode": [
        "cors"
      ],
      "sec-fetch-dest": [
        "empty"
      ],
      "priority": [
        "u=1, i"
      ]
    },
    "path": "/todo-items",
    "endpoint": "Todo List Items",
    "routeValues": {}
  },
  "traceId": "00-01810c8c790b8388e1dfe384dad93899-b84d67278fa1a30b-01"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant