How to select data from multiple tables with LINQ (entities)
I have two tables and corresponding LINQ entities
- product
- order
order has a fk_product_id in the database which is linked to pk_product_id in table product
How can I write a method that returns data from both tables, so that I can hook it up to a repeater or gridview?
I found examples where people are writing joins, but I wonder if开发者_StackOverflow中文版 that's really necessary.
With LINQ you can do something like this:
var results = from o in Order
select new
{
order = o,
product = o.Product
};
Then feed that as a DataSource to your repeater, and then access it in an ItemTemplate or such like this:
<asp:Label Text='<%# Eval("product.Name") %>' />
You can flatten the fields you want from the 2 different objects into a new 'flat' anonymous type. See here.
Use db.orders.include("product").all(); While u had define product entity in order class ...
精彩评论