使用linq连接表并在视图中显示

时间:2014-01-16 05:22:48

标签: c# asp.net-mvc linq linq-to-entities

这是我的代码

public List<InvoiceJoin> ShowIvoiceList()
{
   InvoiceJoin ij = new InvoiceJoin();
   List<InvoiceJoin> list; 
   var data = (from t in _Entity.TblInvoices join t0 in _Entity.TblClients on new { ReceiverCode = t.ReceiverCode } equals new { ReceiverCode = t0.ClientCode }
   select new
   {
      t.RakeNumber,
      t.ReceiverCode,
      t.ConsigneeCode,
      t.InvoiceNumber,
      t.InvoiceDate,
      t.RecordStatus,
      t0.ClientCode,
      t0.ClientDescription,
      t0.ClientAddress1,
      t0.ClientAddress2,
      t0.ClientAddress3,
      t0.ClientCity,
      t0.ClientState,
      t0.ClientCountry,
      t0.ClientZipCode,
    }).ToList();

    foreach (var item in data)
    {
       list.Add(item);
    }
    return list;
}

我的invoicejoin类

public class InvoiceJoin
{
    public TblInvoice invoice { get; set; }
    public string Cdetails { get; set; }
    public string Cname { get; set; }
    public string Caddr { get; set; }
    public string Pname { get; set; }
    public string Paddr { get; set; }
}

它不起作用 我需要在单个视图中显示两个sql表数据列表如何在linq中执行此操作请一些我需要在html表中显示的帮助朋友。 。

2 个答案:

答案 0 :(得分:1)

使用LINQ Union方法,如下所示:

var data = (from t in _Entity.TblInvoices
              join t0 in _Entity.TblClients on new { ReceiverCode = t.ReceiverCode } equals new { ReceiverCode = t0.ClientCode }
              select new
              {
                  t.RakeNumber,
                  t.ReceiverCode,
                  t.ConsigneeCode,
                  t.InvoiceNumber,
                  t.InvoiceDate,
                  t.RecordStatus,
                  t0.ClientCode,
                  t0.ClientDescription,
                  t0.ClientAddress1,
                  t0.ClientAddress2,
                  t0.ClientAddress3,
                  t0.ClientCity,
                  t0.ClientState,
                  t0.ClientCountry,
                  t0.ClientZipCode,
              }).Union( // 2nd linq query with same result set as first here);

答案 1 :(得分:1)

确保你有带有2个参数的构造函数的InvoiceJoin类:invoice和client

class InvoiceJoin
{
   private TblInvoice invoice;
   private TblClient client;
   public InvoiceJoin(TblInvoice invoice,TblClient client)
   {
      this.invoice=invoice;
      this.client=client;
     //...
   }
    public string RakeNumber{ get{return invoice.RakeNumber} set{invoice.RakeNumber=value;}}
   //... ather invoice properties you want to see in grid
    public string ClientCode{ get{return client.ClientCode} set{client.ClientCode=value;}}
   // ...ather clientproperties you want to see in grid
}

加载数据:

List<InvoiceJoin> data = (from invoice in db.TblInvoices
                          join client in db.TblClients
                          on  invoice.ReceiverCode equals client.client 
                          select new{Invoice=invoice,Client=client}).ToList() 
                          .Select(n=>new InvoiceJoin(n.Invoice,n.Client)).ToList()