Explicitly load related entities in many-to-many relationship with Entity Framework over WCF
-
19-06-2021 - |
题
I'm using EF 4.1 with Self-Tracking Entities in a layered application which uses WCF to hand entities back and forth from the client to the server.
A portion of my database contains 3 tables:
Customer
Contact
CustomerContacts
CustomerContacts
contains only the two primary keys of Customer
and Contact
, thus the EDM represents this as navigation properties - Customer.Contacts
and Contacts.Customers
. The CustomerContacts
table is not represented otherwise in the model, meaning there is no CustomerContacts
entity, which I understand and expect as a feature of the EDM Designer when representing many-to-many relationships of this form.
The situation is that I have a list of Customer
s bound to a ComboBox
and wish to load the related Contact
s of a Customer
only at the point when it is selected in the ComboBox
. Put another way, I wish to explicilty load Customer.Contacts
when a Customer
is selected in the ComboBox
. I can't use Customer.ID
in a Where
to fetch the list of Contacts
, since there is no join entity in the model which relates them.
Currently, I am loading another copy of the Customer
, using Include("Contacts")
to get the Contact
s and then setting via selectedCustomer.Contacts = temporaryCustomer.Contacts;
Does anyone know of another method which doesn't require that I fetch a redundant, temporary copy of the Customer
?
解决方案
You already know Id
of selected customer so you can simply pass it to WCF as parameter and query contacts related to customer:
var customerContacts = context.Contacts
.Where(c => c.Customers.Any(cu => cu.Id == passedId));
Anyway you should think about replacing your WCF with STEs with WCF Data Services which are more suitable for this scenarios and support many features (including loading of navigation property) out-of-the-box.