I am developing a MVC3 application in c# and I am using NHibernate for the ORM part. I need to generate a list of all registered customers and their latest order. On the application side, this would require to go through all customers and retrieve all their orders to extract the latest one.
Unneeded overhead, isn’t it?
On the database, I could create a view and model the entity accordingly, but then I cannot create new customers due to the fact that populating a view is not possible. So, any ideas or best practices how you solved such issues? Here’s a sql query that would serve the needed information:
SELECT c.id, c.name, c.description, m.ordernumber AS latest_order, m.unixtime, m.id AS latest_order_id
FROM dbo.customer c
LEFT JOIN dbo.mailorder m ON c.id = m.customer_id
WHERE m.unixtime = (SELECT MAX(unixtime) FROM dbo.mailorder)
Any help is very much appreciated!
Best regards,
Martin
You can use formula to get last order for customer, something like this: