简体   繁体   English

EF Core 3.1:Sequence 不包含带有 FromSqlRaw 查询存储过程的元素

[英]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.我尝试使用 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.我使用在 Stackoverflow 上找到的这个扩展方法,它稍微封装了整个事情。 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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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