【问题标题】:How can I bind a query with a join to a GridView, with a Linq datasource with a business layer and data access layer如何将带有联接的查询绑定到 GridView,以及带有业务层和数据访问层的 Linq 数据源
【发布时间】:2013-03-01 04:14:18
【问题描述】:

我有两个表格要合并显示在一个 GridView 中

foo
fooID  fooName barID
1      Alice   2
2      Bob     1
3      Charlie 1

bar
barID  barTitle
1      Developer
2      Project Manager

(关系和约束已在数据库中定义)

我有一个foo 的 GridView,输出如下

Name    Title
Alice   2
Bob     1
Charlie 1

但我想看看以下内容

Name    Title
Alice   Project Manager
Bob     Developer
Charlie Developer

显然,我的 SQL 应该是这样的:

select fooName as Name, barTitle as Title
from foo join bar on foo.barid = bar.barid

深埋在我的代码中,我有以下内容:

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>();
    }
// ...

我认为在这里我应该能够在 Linq 中构造一个 Join,但我不知道该怎么做。如何修改 Linq 代码来处理加入?

【问题讨论】:

    标签: c# asp.net linq gridview


    【解决方案1】:

    你可以使用这个查询:

    select  a.fooName as Name, b.barTitle as Title from foo a inner join bar b
    on a.barid= b.barid
    

    在你的网格中你也需要改变

    <asp:BoundField DataField="BarID" HeaderText="Title" />
    

    <asp:BoundField DataField="Title" HeaderText="Title" />
    

    等效的 LINQ 查询是:

    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();
    

    【讨论】:

    • 是的,我在我的问题中包含了基本相同的查询。我将如何在 Linq 中实现它或使用我同事建议的其他方法?
    • No Joy... 我收到以下错误:“无法将类型 'System.Collections.Generic.List' 隐式转换为 'System.Collections.Generic.IList'。存在显式转换(您是否缺少演员表?)"
    • ok 试试这个:select new foo{ Name= p.fooName , Title = q.barTitle }).ToList();
    • name和title必须是foo类的属性
    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多