实体框架4 - 代码优先和存储过程

时间:2010-08-30 12:08:02

标签: .net entity-framework stored-procedures code-first

我想用一个使用EF4“Code First”返回表的参数执行存储过程。我只是为了这个目的而使用一些DTO,它不需要返回实体。我试过:

a)使用函数import创建edmx文件,并将其添加到我的ObjectContext中,如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.RegisterEdmx("Model.edmx");
}

但我得到InvalidOperationException说“在使用Fluent API进行代码优先配置后,无法使用现有模型的注册。”

b)访问underling连接并执行以下过程:

    var connection = this.objectContext.UnderlyingContext.Connection;
    connection.Open();
    DbCommand command = connection.CreateCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "booklog.Recommendations";
    command.Parameters.Add(
        new EntityParameter("userId", DbType.Guid) { Value = this.userId });
    var reader = command.ExecuteReader();
    // etc.

,其中

public class MyObjectContext : DbContext
{
    public System.Data.Objects.ObjectContext UnderlyingContext
    {
        get { return this.ObjectContext; }
    }

    // ....
 }

但这种方法不起作用。它会向InvalidOperationException抛出消息“在当前工作空间中找不到为FunctionImport指定的容器'booklog'。”

1 个答案:

答案 0 :(得分:5)

好的,b)是正确的,但不必使用UnderlyingContext,只需ObjectContext.Database.Connection。这是代码:

    var connection = this.objectContext.Database.Connection;
    connection.Open();

    DbCommand command = connection.CreateCommand();
    command.CommandType = CommandType.StoredProcedure;
    command.CommandText = "Recommendations";
    command.Parameters.Add(
        new SqlParameter("param", DbType.Guid) { Value = id });

    var reader = command.ExecuteReader();
    while (reader.Read())
    {
        // ...
    }

    connection.Close();