views:

48

answers:

1

Is there a way to make this code excute in one query with Entity-Framework?

Private Sub LoadFirstPhone(vendor As Vendor)
    If Not vendor.ContactReference.IsLoaded Then _
        vendor.ContactReference.Load(MergeOption.AppendOnly)
    vendor.Contact.Phones.Load(MergeOption.AppendOnly)
End Sub

I want two things:

  1. I want to be able to Load only the first phone, not all of the phones
  2. I want to make it one query, so it doesn't have to make 2 round-trips
+1  A: 

Try this:

From v in context.Vendors
Select New With {
  .Vendor = v,
  .Contact = v.Contact,
  .FirstPhoneNumber = v.Contact.Phones.FirstOrDefault()
}
jeroenh
No chance, since when is ContactReference supposed to have a 'Phones' property??
Shimmy
OK, so I misread your sample. See my edit (you could have interpreted that yourself with a little effort), no need to start bullying though, I'm only offering my help.
jeroenh
Thanks for the update, but is there a way to LOAD the values for existing items, not query the parent vendor, just populate its properties and sub-properties, maybe using CreateEntityReference?
Shimmy
@Shimmy: I don't understand your edit, the ContactReference is no longer loaded? Filling in several navigation properties at once won't be possible AFAIK. My point is that you can write a query to fetch the data you want, but you won't be able to 'attach' the result to the vendor entity.
jeroenh
ContactReference is not a type of Contact, what you wrote before should obviously be a compile-time error.
Shimmy
@Shimmy Now I'm curious. Probably missing something obvious, but what exactly is ContactReference in the code in your question?
jeroenh
ContactReference is a genereated property that returns an EntityReference(Of Contact), all the X-2-One relationships have this property generated in addition to the navigation property itself.
Shimmy
@Shimmy Sorry, I didn't know that... Just realized again that I'm not using the default code generation template with EF on my current project (we're using self tracking entities)...
jeroenh
thanks for trying.if you'll ever get to the answer don't hesitate, as it will help not only me but many people of the dev community!
Shimmy