Ste*_*ves 2 .net stored-procedures entity-framework code-first
我想用一个参数执行存储过程,该参数使用EF4"Code First"返回表.我只是为了这个目的而使用一些DTO,它不需要返回实体.我试过:
a)使用函数import创建edmx文件并将其添加到我的ObjectContext,如下所示:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.RegisterEdmx("Model.edmx");
}
Run Code Online (Sandbox Code Playgroud)
但是我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.
Run Code Online (Sandbox Code Playgroud)
哪里
public class MyObjectContext : DbContext
{
public System.Data.Objects.ObjectContext UnderlyingContext
{
get { return this.ObjectContext; }
}
// ....
}
Run Code Online (Sandbox Code Playgroud)
但这种方法不起作用.它抛出InvalidOperationException消息"在当前工作空间中找不到为FunctionImport指定的容器'booklog'."
好的,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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5004 次 |
| 最近记录: |