I’m trying to associate two entity types in EF4, there is no foreign key available.
Is there any manual tweaks I can do to so when I load an instance of order I get something like:
order.orderID = 455
order.date = 2012-08-12
order.OrderItems = <List>OrderItem // OrderItem being the other entity I want to map on order
I guess I’ll have to do this manually when I Select() an order and set it’s OrderItems property since no FKs are avail.
Am I on the right track ?
**EDIT:
I was able to create an association between orders and orderitems and here’s a Select() method I have for an order:
public Order Select(long orderID)
{
using (var ctx = new BillingSystemEntities())
{
var res = from n in ctx.Orders
where n.OrderID == orderID
select n;
if (res.Count() == 0)
return null;
else
return res.First();
}
}
According to SQL Profiler, EF is not doing any JOIN on OrderItem table. I guess I need to load them into the OrderItems navigation property myself ?
You just need to include the
OrderItemsin your query:Also
FirstOrDefaultis more appropriate here than yourCount()...First()construct because it hits the database only once whileCount()andFirst()will issue a separate query each.You can write it even more compact with: