Entity Framework4.1调用存储过程示例

一、调用返回单个值的存储过程

1.存储过程

Create PROCEDURE [dbo].[Do]
    @a int,
    @b int
AS
BEGIN
    select @a + @b  --不能用return
END

2.DbContext对象中的方法

public int Do(int a, int b)
{
    SqlParameter[] parameters = new SqlParameter[]{
        new SqlParameter("@a", SqlDbType.Int),
        new SqlParameter("@b", SqlDbType.Int)
    };
    parameters[0].Value = a;
    parameters[1].Value = b;

    //Database是testContext对象属性,从DbContext继承而来
    return Database.SqlQuery<int>("exec Do @a,@b", parameters).FirstOrDefault();
}

3.调用示例

testContext context = new testContext();
int result = context.Do(7, 8);
Console.WriteLine(result);

二、调用返回表的存储过程

1.存储过程

Create PROCEDURE [dbo].[Do]
    @a int,
    @b int
AS
BEGIN
    select @a as f1, @b as f2 --必须有f1,f2
    union all
    select 10 as f1,20 as f2
END

2.DbContext对象中的方法

public List<TestClass> Do(int a, int b)
{
    SqlParameter[] parameters = new SqlParameter[]{
        new SqlParameter("@a", SqlDbType.Int),
        new SqlParameter("@b", SqlDbType.Int)
    };
    parameters[0].Value = a;
    parameters[1].Value = b;

    return Database.SqlQuery<TestClass>("exec Do @a,@b", parameters).ToList();
}

TestClass类:
public class TestClass
{
    public int f1 { get; set; }
    public int f2 { get; set; }
}

3.调用示例

testContext context = new testContext();
List<TestClass> test = context.Do(7, 8);
foreach (TestClass item in test)
    Console.WriteLine("{0},{1}", item.f1, item.f2);


评论: 0 | 引用: 0 | 查看次数: 4097
发表评论
登录后再发表评论!