简体   繁体   中英

EF Core 3.1: Sequence contains no elements with FromSqlRaw query a stored procedure

I try to query a stored procedure with Entity Framework Core 3.1. I made a really simple test project.

Stored Procedure:

ALTER PROCEDURE [dbo].[prcTest]
AS
BEGIN

    SET NOCOUNT ON;

    select tbl_Postalcode.PST_T_PostalCode AS Postalcode
    from tbl_Postalcode
END

Entity:

public class Test
{
    string Postalcode { get; set; }
}

I use this extensions Methods, found on Stackoverflow, that encapsulate the whole thing a bit. But nothing special.:

public static class DbContextExtensions
{
    public static IList<T> SqlQuery<T>(this DbContext context, string sql, params object[] parameters) where T : class
    {
        using (var dbcontext = new ContextForQueryType<T>(context.Database.GetDbConnection()))
        {
            return dbcontext.Set<T>().FromSqlRaw(sql, parameters).AsNoTracking().ToList();
        }
    }

    public static async Task<IList<T>> SqlQueryAsync<T>(this DbContext context, string sql, params object[] parameters) where T : class
    {
        using (var dbcontext = new ContextForQueryType<T>(context.Database.GetDbConnection()))
        {
            return await dbcontext.Set<T>().FromSqlRaw(sql, parameters).AsNoTracking().ToListAsync();
        }
    }

    private class ContextForQueryType<T> : DbContext where T : class
    {
        private readonly System.Data.Common.DbConnection connection;

        public ContextForQueryType(System.Data.Common.DbConnection connection)
        {
            this.connection = connection;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(connection, options => options.EnableRetryOnFailure());

            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<T>().HasNoKey();
            base.OnModelCreating(modelBuilder);
        }
    }
}

Then i execute the query like this:

var result = await _myContext.SqlQueryAsync<Test>("Exec prcTest");

And i get this error:

AggregateException: One or more errors occurred. (Sequence contains no elements)
System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions)

InvalidOperationException: Sequence contains no elements
System.Linq.ThrowHelper.ThrowNoElementsException()


System.Threading.Tasks.Task.ThrowIfExceptional(bool includeTaskCanceledExceptions)
System.Threading.Tasks.Task<TResult>.GetResultCore(bool waitCompletionNotification)
System.Threading.Tasks.Task<TResult>.get_Result()
System.Text.Json.JsonPropertyInfoCommon<TClass, TDeclaredProperty, TRuntimeProperty, TConverter>.GetValueAsObject(object obj)
System.Text.Json.JsonSerializer.HandleEnumerable(JsonClassInfo elementClassInfo, JsonSerializerOptions options, Utf8JsonWriter writer, ref WriteStack state)
System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, int originalWriterDepth, int flushThreshold, JsonSerializerOptions options, ref WriteStack state)
System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Can anyone give me an idea what the specific problem is?

Found the solution. The error message is not helpful and very confusing.

The solution:

Make the property public. It is so obvious but the error message confused me.

public class Test
{
    public string Postalcode { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM