我想用一个使用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'。”
答案 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();