zoukankan      html  css  js  c++  java
  • How to call a stored procedure in EF Core 3.0 via FromSqlRaw(转载)

    问:


    I recently migrated from EF Core 2.2 to EF Core 3.0.
    Unfortunately, I haven't found a way to call a stored procedure that returns an entity.
    In EF Core 2.0 it was possible:

    var spParams = new object[] { "bla", "xx" };
    var createdPath = ModelContext.Paths.FromSql("AddNodeWithPathProc  @p0, @p1", spParams).Single();

    In EF Core 3.0 the method FromSQL is replaced with FromSqlRaw. However, I didn't manage to successfully call a stored procedure and then process the value. This is useful when the stored procedure inserts data into the database.
    So in EF Core 3.0, I use this code:

    var createdPath = ModelContext.Paths.FromSqlRaw("AddNodeWithPathProc @p0, @p1", spParams).Single();

    but it will throw an exception, because the generated SQL is invalid and looks something like this:

    exec sp_executesql N'SELECT TOP(2) [p].[PathId], [p].[Level], [p].[NodeId], [p].[NodePath], [p].[NodePathString]
    FROM (
         @sql @p0, @p1
    ) AS [p]',N'@p0 nvarchar(4000),@p1 nvarchar(4000), @sql nvarchar(100)',@p0=N'1a',@p1=N'', @sql=N'AddNodeWithPathProc'

    I tried quite a few variations, but without success.
    I'm starting to think that it is not possible to run stored procedures with ModelContext.[IQueryable].FromSqlRaw. In my opinion this kind defeats one of the major reasons for FromSqlRaw because, for normal select statements, LINQ is normally good enough.
    Does anyone know how to use stored procedures in combination with FromSqlRaw in EF Core 3.0? Any help is greatly appreciated.
    Thanks in advance
    PS: I know you can execute a stored procedure with this.Database.ExecuteSqlRaw(SQL, parameters). However, that way it is not possible retrieve any entities that the stored procedure queries.

    答:


    Try .ToList() instead of .Single(). .Single() is generating the "TOP(2)" wrapper.

    var createdPath = ModelContext.Paths.FromSqlRaw("AddNodeWithPathProc  {0}, {1}", nodeTitle, parentPathString).ToList();

    原文链接

  • 相关阅读:
    ajax traditional
    阿里云OSS NET SDK 引用示范程序
    js对象的两种写法
    BZOJ NOIP提高组十连测第一场
    ikbc 时光机 F87 Ctrl 失灵 解决办法
    【读书笔记】阅读的危险
    51nod 1118 机器人走方格 解题思路:动态规划 & 1119 机器人走方格 V2 解题思路:根据杨辉三角转化问题为组合数和求逆元问题
    【算法】求逆元模板
    【复习资料】软件工程之快速原型模型
    VirtualBox安装linux mint教程
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/11808699.html
Copyright © 2011-2022 走看看