2

我想使用一个参数执行存储过程,该参数使用 EF4“代码优先”返回表。出于这个目的,我可以使用一些 DTO,它不必返回实体。我试图:

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

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

但我InvalidOperationException说“在使用 fluent API 开始代码优先配置后,无法使用现有模型的注册。”

b) 访问下属连接并执行程序:

    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'。”

4

1 回答 1

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();
于 2010-08-30T22:21:51.543 回答