【问题标题】:Entity Framework 4 - Code First and Stored Procedures实体框架 4 - 代码优先和存储过程
【发布时间】:2010-08-30 12:08:02
【问题描述】:

我想使用一个参数执行存储过程,该参数使用 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'。”

【问题讨论】:

  • 在 EF 4 Code First CTP 5 中,DbContext 中没有 ObjectContext 属性。相反,请使用 Database 属性。

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


【解决方案1】:

好的,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();

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多