从使用EF6的条件选择的存储过程捕获结果

时间:2015-03-07 09:17:21

标签: stored-procedures entity-framework-6

我使用存储过程来调用EF6,其结果因所满足的条件而异。如何在EF6中捕获此类结果?

样本程序:

create procedure udsp_get_category
(
    @a int =0
)
as
if @a = 1
Begin
    select top 1 pk_cat_id,cat_name,cat_is_active from category_master
End
Else if @a = 0
Begin 
    select top 1 pk_cattp_id,cattp_name,cattp_is_active from category_type_master 
End
Else 
Begin
    select -1 as no_result
End

结果完全不同于任何条件,请指导在Entity Framework中捕获此类结果集!感谢。

2 个答案:

答案 0 :(得分:1)

很大程度上取决于您的模型的外观。假设您有一个类别模型,并相应地映射了字段名称,那么这将是一个开始:

public Category GetCategoryById(int categoryId)
{
    Category category;

    using (var context = new NorthwindData())
    {
        SqlParameter categoryParam = new SqlParameter("@a", categoryId);
        category = context.Database.SqlQuery<Category>("udsp_get_category @a", categoryParam).FirstOrDefault();
    }

    return category;
}

EF上有很多关于存储过程的好文章。 http://www.lucbos.net/2012/03/calling-stored-procedure-with-entity.html

答案 1 :(得分:1)

如果您的所有查询都具有相同的形状,这只适用于EF。例如:

create procedure udsp_get_category
(
    @a int =0
)
as
if @a = 1
Begin
    select top 1 pk_cat_id as [Id],
                 cat_name as [Name],
                 cat_is_active as [Active],
                 1 as [IsMaster]
    from category_master
End
Else if @a = 0
Begin 
    select top 1 pk_cattp_id as [Id],
                 cattp_name as [Name],
                 cattp_is_active as [Active]
                 0 as [IsMaster]
    from category_type_master 
End
Else 
Begin
    select -1 as [Id],
           null as [Name],
           null as [Active]
           -1 as [IsMaster]
End

现在,您可以在将IdNameActiveIsMaster作为属性的类中捕获结果。