Stored Procedures and EF Code First

狂风中的少年 提交于 2020-01-01 04:39:06

问题


I would like to use a stored procedure to retrieve entities from a DB, I don't care about tracking changes. I just need all entities be resolved including related ones.

  1. Do I have to use SqlCommand?

  2. What about complex properties, will they be resolved too?

  3. Any other limitations you could tell me about?

Thanks!


回答1:


General answer about using stored procedures in EF is here so stored procedure in pure EF will not handle navigation properties. The answer also mentioned EFExtensions but that is not available in DbContext API.

To execute stored procedure in DbContext API use:

var entities = context.Database.SqlQuery<MyEntity>(...);

DbContext API doesn't offer any function import like EDMX and ObjectContext API.




回答2:


Stored Procedures are not supported in Code First. So yes, you'll have to use SqlCommand or whatever your DB of choice provides if you intend on using Code First.

Stored Procedures ARE supported in DB First or Model First.




回答3:


Try function import: http://msdn.microsoft.com/en-us/library/dd456824.aspx




回答4:


By Looking at database first approach, in auto generated context class it defines stored procedures as a virtual functions, Here I share a function from my project, this stored procedure returns a complex type of question.

public virtual ObjectResult<Question> GetMyInnerQuestions(Nullable<int> id)
        {
            var idParameter = id.HasValue ?
                new ObjectParameter("Id", id) :
                new ObjectParameter("Id", typeof(int));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<Question>("GetMyInnerQuestions", idParameter);
        }

I used this in my code first do I can call stored procedures like functions as:

IQueryable<Question> questions = db.GetMyInnerQuestions(id).AsQueryable();

Hope this help



来源:https://stackoverflow.com/questions/5544061/stored-procedures-and-ef-code-first

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