Entity Framework: how to do correct “Include” on custom type

别说谁变了你拦得住时间么 提交于 2019-12-20 00:56:42

问题


Suppose we have 2 types, mapped to a Database via EF 4.

Schedule 1.....1 Visit

Also, we have third custom view type

public class ScheduleView
{
    public Schedule Schedule { get; set; }
    public Visit Visit { get; set; }
}

So we can write the join query

var query = Context.Schedule.Join(Context.Visit
,/*Schedule join key definition*/,/*Visit join key definition*/,
(scheduleView, visit) => new ScheduleView {Schedule = scheduleView, Visit = visit})

The problem is that I need to load also Patient property of Visit type. But when I write

query = (query as ObjectQuery<ScheduleView>).Include("Visit.Patient");

I receive a runtime error

Unable to cast the type 'System.Linq.IQueryable1' to type 'System.Data.Objects.ObjectQuery1'. LINQ to Entities only supports casting Entity Data Model primitive types.

So, the question is - how to force query to include something within my custom type?


回答1:


Finally, developed some ugly workaround - introduced new member in custom type and explicitly queried for it.

public class ScheduleView
{
    public Schedule Schedule { get; set; }
    public Visit Visit { get; set; }
    **public Patient Patient{ get; set; }**
}

    var query = Context.Schedule.Join(Context.Visit
    ,/*Schedule join key definition*/,/*Visit join key definition*/,
    (scheduleView, visit) => new ScheduleView 
{Schedule = scheduleView, Visit = visit, **Patient = visit.Patient**})

Now I have Patient loading properly in my custom type. Amusing, but when I investigate ScheduleView.Visiting.Patient after introducing ScheduleView.Patient I found it also loaded. Cant get the EF logic in this case. And dunno how to force loading ScheduleView.Visiting.Patient without having to load useless ScheduleView.Patient :(




回答2:


The error is spot on. Your trying to create an ObjectQuery (LINQ-Entities IQueryable), with a type (ScheduleView) which does not exist in your Model.

You can project into this type, sure - but not affect the query with it.

Will something like this work? (off the top of my head, untested)

var scheduleViews = (from s in ctx.Schedules
                     join v in ctx.Visits.Include("Patient") 
                     on v.ScheduleId equals s.ScheduleId
                     select new ScheduleView 
                     { 
                        Schedule = s, 
                        Visit = v 
                     }).ToList();

Your main problem is ObjectQuery<ScheduleView> is not translatable to a store expression. So do your include on the Visits entity set, not the IQueryable.

HTH



来源:https://stackoverflow.com/questions/4021755/entity-framework-how-to-do-correct-include-on-custom-type

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