2

我有一个存储过程,您可以在下面找到逻辑,现在当我将此 sp 带到 EF {版本 5.0} 时,此 sp 将返回类型为 int。

Create Proc  SP_GetResultBasedOnFilterForCoverage
(
 @AgeID int,
 @IncomeID int,
 @GenderID int,
 @EducationID int,
 @ProductID int
)
as
set nocount on
Declare  @query varchar(max), @index  int, @totalrow int, @coverageTotal bigint
IF OBJECT_ID('tempdb..#SecondDataSet') IS NOT NULL
    DROP TABLE #SecondDataSet
Create table #SecondDataSet
(
CoverageID int,
  Coverage varchar(100),
  Percentage float
) 

Declare @CoverageTable Table
(
  id int identity(1,1),
  CoverageID  int,
  Coverage varchar(100),
  CoverageCount int   
)

insert into @CoverageTable
(CoverageID,Coverage,CoverageCount)
Select TCPC.CoverageID,Coverage.Coverage, COUNT(CustomerID) from TBL_Customer_Product_Choice as  TCPC
inner join 
Tbl_Coverage as coverage
on 
coverage.CoverageID = TCPC.CoverageID
group by 
TCPC.CoverageID,coverage.Coverage



set @index = 1;
Select @totalrow =  COUNT(ID) from @CoverageTable

While(@index <= @totalrow)
begin
Declare @CurrentCoverageID int
Select  @coverageTotal = CoverageCount, @CurrentCoverageID = CoverageID from @CoverageTable where id = @index
set @query  = '
 Insert into #SecondDataSet 
 (Percentage,CoverageID,Coverage)

Select Round((Cast(COUNT(TCPC.CustomerID) as float)/cast('+cast(@coverageTotal as varchar)+' as  bigint)) * 100,1)  as Percentage ,
TCPC.CoverageID ,TC.Coverage 
from  Tbl_customer_Product_Choice as TCPC
inner  join 
Tbl_Coverage as  TC
on 
TCPC.CoverageID = TC.CoverageID
Where productID = cast('+cast(@ProductID as varchar)+'as int)  and TCPC.CoverageID = cast('+ cast(@CurrentCoverageID as varchar)+' as  int)'

if(@AgeID <> 0)
begin

  set  @query += ' and  AgeID = ' + CAST(@AgeID as  varchar);
End

if( @IncomeID != 0)
begin
  set  @query += ' and  IncomeID = ' + CAST(@IncomeID as  varchar);
End

if(@EducationID != 0)
begin
  set  @query += ' and  EducationID = ' + CAST(@EducationID as  varchar);
End

if(@GenderID > -1)
begin
  set  @query += ' and  GenderID = ' + CAST(@GenderID as  varchar);
End

set @query += ' group  by  TCPC.CoverageID,TC.Coverage
order by  COUNT(TCPC.CustomerID) desc
'
Exec(@query)
set  @index = @index + 1;
end

Select * from #SecondDataSet
4

1 回答 1

1

我最近遇到了这个问题。EF 不能自动生成 SP。我们应该手动添加它。结果,我应用了以下方法。

它是我的示例 SP:


CREATE TABLE #LocalTempTable
(
    c1 INT,
    c2 INT, 
    c3 NVARCHAR(50),
    c4 INT
)

SELECT * FROM #LocalTempTable

添加一个新的复杂类型(用于临时表返回列):

1-.edmx从解决方案资源管理器中打开文件

2-右键单击打开窗口中的空白空间,然后“添加新 -> 复杂类型”

3-重命名类型并右键单击模型浏览器上的重命名类型,然后“添加-> 标量属性-> COLUMN_TYPE”

我的 SP 返回 4 列。int32, int32, string, int32. 如果返回类型是nullable您可以从属性窗口更改

5- 现在我们可以从数据库中导入 SP。右键单击模型浏览器上的函数导入,然后“添加函数导入”

6- 编写自定义名称(注意:在代码隐藏后使用此名称)选择存储过程。勾选复杂,选择创建的复杂类型然后确定。

现在测试SP

DBEntities db = new SIRAMATIKEntities();
List<complex_type> result= db.FunctionName(data).ToList();

如果返回的列名不同的复杂类型列,您可以从 Mapping Details 中更改。在模型浏览器中右键单击创建的函数,然后单击“函数导入映射”。

我希望它有所帮助。如果拼写错误,我很抱歉。我用翻译。

于 2016-07-28T11:23:21.300 回答