实体框架核心,存储过程

时间:2017-04-26 22:10:27

标签: entity-framework

我对如何使用Entity Framework Core使用存储过程感到困惑。如果存储过程返回匿名类型,我该如何检索数据?如果返回类型不是匿名的,我该怎么办?如何添加输入/输出参数?

我问这些问题,因为我看到的每个地方都有不同的答案。我猜EF Core正在迅速发展,微软正在涉及很多想法。

3 个答案:

答案 0 :(得分:1)

  

如何添加输入/输出参数?

我要回答你的这个问题。

下面是一个带有两个输入和两个输出参数的TSQL存储过程

CREATE PROCEDURE [dbo].[yourstoredprocedure] 
-- Add the parameters for the stored procedure here
    @varone bigint
    ,@vartwo Date
    ,@varthree double precision OUTPUT
    ,@varfour bigint OUTPUT
AS
BEGIN
  -- SET NOCOUNT ON added to prevent extra result sets from
  -- interfering with SELECT statements.
  SET NOCOUNT ON;

  -- YOUR CODE HERE
  SET @varthree = 10.02;
  SET @varfour = @varone;
  return;
END

现在使用Entity Framework Core

执行此存储过程
MyContext.Database
                   .ExecuteSqlCommand(@"EXECUTE [yourstoredprocedure] " +
                                       " {0} " +
                                       ", {1} " +
                                       ",@varthree OUTPUT " +
                                       ", @varfour OUTPUT ", dataOne, dataTwo, outputVarOne, outputVarTwo);


var outputResultOne= outputVarOne.Value as double?;
var outputResultTwo= outputVarTwo.Value as long?;

您可以使用上面的参数化查询简单地传递输入。您还可以创建命名参数。比如输出参数,我创建了两个命名参数 -

var outputVarOne = new SqlParameter
        {
            ParameterName = "@varthree ",
            DbType = System.Data.DbType.Double,
            Direction = System.Data.ParameterDirection.Output
        };
var outputVarTwo = new SqlParameter
        {
            ParameterName = "@varfour ",
            DbType = System.Data.DbType.Int64,
            Direction = System.Data.ParameterDirection.Output
        };

这就是使用EF Core执行带输入和输出参数的存储过程的方法。希望这有助于某人。

答案 1 :(得分:0)

您可能会使用StoredProcedureEFCore这样的扩展名

那么用法就更直观了。

列表行= null;

-- scale.lua
-- Usage: lua scale.lua input.bin output.bin
-- Scale an image by skipping alternate lines and alternate columns

-- Set up width, height and bytes per pixel
w   = 640
h   = 480
bpp = 2    

-- Open first argument for input, second for output
inp = assert(io.open(arg[1], "rb"))
out = assert(io.open(arg[2], "wb"))

-- Read image, one line at a time
for i = 0, h-1, 1 do
   -- Read a whole line
   line = inp:read(w*bpp)

   -- Only use every second line
   if (i % 2) == 0 then
      io.write("DEBUG: Processing row: ",i,"\n")
      -- Build up new, reduced line by picking substrings
      reduced=""
      for p = 1, w*bpp, bpp*2 do
         reduced = reduced .. string.sub(line,p,p+bpp-1)
      end
      io.write("DEBUG: New line length in bytes: ",#reduced,"\n")
      out:write(reduced)
   end
end

assert(out:close())

答案 2 :(得分:-1)

此解决方案提供了调用存储过程并将返回值映射到已定义(非模型)实体的方法。 https://github.com/verdie-g/StoredProcedureDotNetCore

Microsoft解决此问题:  “SQL查询只能用于返回作为模型一部分的实体类型。我们的backlog上有一个增强功能,可以从原始SQL查询中返回特殊类型。” https://docs.microsoft.com/en-us/ef/core/querying/raw-sql

以下是GitHub中跟踪的问题:https://github.com/aspnet/EntityFramework/issues/1862