簡體   English   中英

EF Core 3.1:Sequence 不包含帶有 FromSqlRaw 查詢存儲過程的元素

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

我嘗試使用 Entity Framework Core 3.1 查詢存儲過程。 我做了一個非常簡單的測試項目。

存儲過程:

ALTER PROCEDURE [dbo].[prcTest]
AS
BEGIN

    SET NOCOUNT ON;

    select tbl_Postalcode.PST_T_PostalCode AS Postalcode
    from tbl_Postalcode
END

實體:

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

我使用在 Stackoverflow 上找到的這個擴展方法,它稍微封裝了整個事情。 但沒什么特別的。:

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);
        }
    }
}

然后我執行這樣的查詢:

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

我得到這個錯誤:

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)

誰能告訴我具體的問題是什么?

找到了解決辦法。 錯誤消息沒有幫助,而且非常混亂。

解決方案:

將財產公之於眾。 這很明顯,但錯誤消息讓我感到困惑。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM