How to return values from a dynamic SQL Stored Procedure to the Entity Framework?

前端 未结 7 1518
再見小時候
再見小時候 2020-12-15 01:49

I have a Stored Procedure which executes some dynamic SQL. I want to use this Stored Procedure in entity framework 4, but when I try to create a complex type the procedure r

相关标签:
7条回答
  • 2020-12-15 02:06

    Well, if EF cannot recognize what your stored procedure must return then create your complex type ahead of time. You can create a complex type by right clicking any where on the model and and add a complex type. Next when you import your stored procedure, you can choose your complex type from the dropdown.

    0 讨论(0)
  • 2020-12-15 02:07

    Try the below script this is working good.

    BEGIN TRAN
    
    DECLARE @Result varchar(max),@Table varchar(max),@Column varchar(max)
    
    set @Column= 'CategoryName,CategoryID'
    set @Table='Category'
    set @Result= ' select ' + @Column + ' from '+@Table
    
    exec(@Result)
    
    
    ROLLBACK
    
    0 讨论(0)
  • 2020-12-15 02:10

    try this

    CREATE PROCEDURE sp_calculatesalary(@EmployeeId as int)   
    AS
       DECLARE @dynsql VARCHAR(500)=' Salary,Username FROM employee WHERE EmployeeId=@empID'    
       EXEC sp_executesql @dynsql,'@empID INT',@empID=@EmployeeID
       SELECT 1 AS salary,2 AS username
    

    Believe me. That is enough.

    Or you can simply create a complex type based on your query result , and then use collection of the complex type as your query result.

    0 讨论(0)
  • 2020-12-15 02:11

    well, i think this is what you are looking for:

    create procedure sp_calculatesalary
        @employeeId int
    as
        declare @sql nvarchar(max);
        @sql='select salary, username from employee
                where employeeId=' + cast(@employeeId as nvarchar(10));
    
        declare @t table (salary float, username varchar(50));
        insert into @t exec(@sql);
    
        select salary, username from @t;
    return
    

    this will generate a public partial class sp_calculatesalary_Result in entity framework based DAL.

    0 讨论(0)
  • 2020-12-15 02:16

    Perhaps you could consider parameterized SQL, if you must do dynamic queries:

    CREATE PROCEDURE sp_calculatesalary(@EmployeeId as int)  
    as 
    begin   
        declare @dynsql varchar(500)   
        declare @params nvarchar(500)
        declare @salary money
        declare @username varchar(50)
        set @dynsql='Select @sal=Salary,@usernm=Username from employee where EmployeeId=@empID'   
        set @params='@empID int, @sal money OUTPUT, @usernm varchar(50) OUTPUT'
        exec sp_executesql @dynsql, @params, @empID=@EmployeeID, @sal=@salary OUTPUT, @usernm = @username OUTPUT
        SELECT @salary, @username
    end
    
    0 讨论(0)
  • 2020-12-15 02:20

    have you tried giving aliases to your last Select:

    select @Salary as Salary, @UserName as UserName
    
    0 讨论(0)
提交回复
热议问题