开发者

How can you populate a model including child collections from a stored procedure in EF Code First

I have a project using Entity Framework code first.

For various reasons one of the linq queries just doesnt perform well and I want to replace it with a stored procedure call.

The following code works fine for calling a stored procedure and converting the result into a List.

IEnumerable<Activ开发者_StackOverflow社区ity> activities =
    ((IObjectContextAdapter)MyContext)
       .ObjectContext.ExecuteStoreQuery<Activity>("GetActivities").ToList();

However I also want some includes on the activity model to load one of the child collections on that object. For example Activity has a Virtual List collection. Is there a way I can in my stored procedure also return the Tags for each activity.

If I do the following does not work

SELECT
   Activities.ID,
   Activities.Name,
   Tags.ID,
   Tags.Name
FROM
   Activities
   LEFT JOIN ActivityTags ON ActivityTags.ActivityID = Activities.ID
   LEFT JOIN Tags ON Tags.ID = ActivityTags.TagID

It errors in the C# saying its not a valid activity. If I remove the Tags bit from the stored procedure so it just selects from the Activities table it works fine.

I'm not sure if what I'm asking is possible with a stored procedure using the entity framework or not. If not I may have to resort to using the SqlCommand and building the model from my result set myself.


It is not possible. Automatic entity population works only for flat objects = you can populate Activity but not its relation. You must use standard ADO.NET if you want to load relations as well but in such case it would be better to modify your stored procedure to return separate result set for each table to reduce amount of transferred data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜