Reputation: 4987
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 ?
Upvotes: 2
Views: 404
Reputation: 177133
You just need to include the OrderItems
in your query:
public Order Select(long orderID)
{
using (var ctx = new BillingSystemEntities())
{
var res = from n in ctx.Orders.Include("OrderItems")
where n.OrderID == orderID
select n;
return res.FirstOrDefault();
}
}
Also FirstOrDefault
is more appropriate here than your Count()...First()
construct because it hits the database only once while Count()
and First()
will issue a separate query each.
You can write it even more compact with:
public Order Select(long orderID)
{
using (var ctx = new BillingSystemEntities())
{
return ctx.Orders.Include("OrderItems")
.FirstOrDefault(n => n.OrderID == orderID);
}
}
Upvotes: 3