【问题标题】:Execute StoredProcedure in CodeFirst 4.1在 Code First 4.1 中执行存储过程
【发布时间】:2011-04-25 09:13:04
【问题描述】:

我理解存储过程映射不支持我的理解是我应该能够调用存储过程。

我有很多复杂的存储过程,通过设计器,我可以创建一个复杂的类型,而且一切都很好。

现在在代码中首先让我们假设我有以下存储过程,只是把一些愚蠢的东西放在一起给出一个想法。我想返回一个有 1 个地址的学生。

在代码中,我有一个学生和地址实体。但是没有StudentAddressEntity,因为它是一个链接表。

我尝试了以下方法,但出现错误

'."} 附近的语法不正确
System.Data.Common.DbException {System.Data.SqlClient.SqlException}

ALTER Procedure [dbo].[GetStudentById]
   @StudentID int
AS
   SELECT  *
   FROM Student S
   left join StudentAddress SA on S.Studentid = sa.studentid
   left join Address A on SA.AddressID = A.AddressID
   where S.StudentID = @StudentID

C#代码:

using (var ctx = new SchoolContext())
{
   var student = ctx.Database.SqlQuery<Student>("GetStudentById,@StudentID",
                                                new SqlParameter("StudentID", id));
}

有任何示例如何调用 sp 并首先在代码中填充 complexType,使用 out 参数等。我可以挂接到 ADO.NET 吗?

尝试只返回所有不带参数的学生的 SP 我得到这个错误

System.SystemException = 无法为属性创建值 'StudentAddress' 类型 'CodeFirstPrototype.Dal.Address'。仅有的 原始类型的属性是 支持。

是因为我在某种程度上忽略了链接表吗?

有什么建议吗?

【问题讨论】:

    标签: entity-framework stored-procedures ef-code-first entity-framework-4.1


    【解决方案1】:

    我相信你的例外实际上是:

    ',' 附近的语法不正确。

    因为这是无效的声明:"GetStudentById,@StudentID"。它应该没有逗号:"GetStudentById @StudentID"

    EF 中存储过程的问题在于它们不支持加载导航属性。 EF 将仅实现主要实体,并且不会加载导航属性。例如,EFExtensions 解决了这个问题。 EFExtensions 用于 ObjectContext API,因此您必须检查它是否也可用于 DbContext API。

    【讨论】:

      【解决方案2】:

      使用 EFExtentions 看起来像

      using (var context = new SchoolContext())
      {
          var command = context.CreateStoreCommand("GetStudentById", CommandType.StoredProcedure,
            new SqlParameter("StudentID", id));
      
          using (command.Connection.CreateConnectionScope())
          using (var reader = command.ExecuteReader())
          {
              // use the reader to read the data
              // my recommendation is to create a Materializer using EFExtensions see 
              // http://blogs.msdn.com/b/meek/archive/2008/03/26/ado-entity-framework-stored-procedure-customization.aspx
      
              // ex
              var student = Student.Materializer.Materialize(reader).SingleOrDefault();
      
              return student;
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-18
        • 2010-09-15
        • 2012-05-15
        • 1970-01-01
        • 2023-04-02
        • 1970-01-01
        相关资源
        最近更新 更多