问题
I have two tables that I'd like to join together display in a GridView
foo
fooID fooName barID
1 Alice 2
2 Bob 1
3 Charlie 1
bar
barID barTitle
1 Developer
2 Project Manager
(relationships and constraints have been defined in the database)
I've got a GridView for foo that outputs like this
Name Title
Alice 2
Bob 1
Charlie 1
But I'd like see the following
Name Title
Alice Project Manager
Bob Developer
Charlie Developer
Clearly, my SQL would look like:
select fooName as Name, barTitle as Title
from foo join bar on foo.barid = bar.barid
Buried deep in my code I have the following:
FooDAL.cs
// ...
namespace ourDAL{
// ...
public class fooDAL : ICRUD <foo>, IDisposable //ICRUD is just an interface
{
// ...
ourPoco context; // ourPoco was auto generated by a template from our
// database and an EDMX file.
public fooDAL()
{
context = new ourPoco;
}
// ...
public IList<Cfoo> FindAll()
{
return (from c in context.foo
select c).ToList<foo>();
}
// ...
I think in here I should be able to construct a Join in Linq, but I'm not sure how to do that. How can I mod the Linq code to handle the join?
回答1:
You can use this query:
select a.fooName as Name, b.barTitle as Title from foo a inner join bar b
on a.barid= b.barid
also in your grid you need to change from
<asp:BoundField DataField="BarID" HeaderText="Title" />
to
<asp:BoundField DataField="Title" HeaderText="Title" />
The equivalent LINQ query would be:
var a = (from p in foo
join q in bar
on p.barid equals q.barid
select new { Name= p.fooName , Title = q.barTitle }).ToList();
来源:https://stackoverflow.com/questions/15150363/how-can-i-bind-a-query-with-a-join-to-a-gridview-with-a-linq-datasource-with-a