views:

417

answers:

2

Starting here:

public class Customer
{
  public int CustomerID { get; set; }
  public string CustomerName { get; set; }  
  public IList<Order> Orders { get; set; }
}

public class Order
{
  public int OrderID { get; set; }
  public int CustomerID { get; set; }
}

What would be the linq query that you write to retrieve all Orders from all Customers?

Something to the effect of:

IList<Order> orders = new List<Order>();
foreach (Customer c in Customers)
{
    orders.Union(c.Orders);
}

I tried the following but it throws an "nhibernate collection was not an association" exception:

var orders = from c in Customers
             select c.Orders;

I know I'm missing something, but I can't find a way to achieve this in linq.

+2  A: 
var orders = from c in db.Customers
    from o in c.Orders
    select o;

Or

var orders = db.Customers.SelectMany(c => c.Orders);

Will it work in linq for nhibernate? I don't know.

David B
I tried this too, still getting the Error: collection was not an association: Orders.
Make sure nhibernate is aware of the association between Customer and Order. I bet there's an xml file somewhere that requires tampering.
David B
I've been trying to play with the nhibernate xml mapping file with no success so far. I'm using the <class> entity for the Customer object and the <bag> collection entity for the Orders. There are different ways and things involved to set up the relationship (key, one-to-many, foreign-key, composite-element, etc.) some work together but others don't... I'll post something when I figure this one out. Thanks for the help so far.
A: 

Make sure your foreign key constraint is setup properly from [Order].[CustomerID] to [Customer].[ID] in the database.

takobell
I do have the foreigh key association setup properly in the database. If I use the looping construct I wrote in my initial question, everything works fine.