Execute StoredProcedure in CodeFirst 4.1

巧了我就是萌 提交于 2019-12-05 10:02:29

I believe that your exception actually is:

Incorrect syntax near ','.

because this is invalid statement: "GetStudentById,@StudentID". It should be without comma: "GetStudentById @StudentID".

The problem with stored procedures in EF is that they don't support loading navigation properties. EF will materialize only the main entity and navigation properties will not be loaded. This is solved for example by EFExtensions. EFExtensions are for ObjectContext API so you will have to check if it is also usable for DbContext API.

Using EFExtentions it will look something like

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;
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!