【问题标题】:How to display the data of two tables in a view using LINQ lambda expression in ASP.Net MVC?如何在 ASP.Net MVC 中使用 LINQ lambda 表达式在视图中显示两个表的数据?
【发布时间】:2019-06-13 01:04:19
【问题描述】:

我很难尝试使用 ASP.net MVC 中的 linq lambda 表达式将两个表中的数据显示到视图中。

我试过这段代码:

var idSearchJoin = payoutdb.payout_transaction    // your starting point - table in the "from" statement
                .Join(payoutdb.payout_remittance, // the source table of the inner join
                transaction => transaction.transid, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
                remit => remit.transid,   // Select the foreign key (the second part of the "on" clause)
                (transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
                .Where(transactremit => transactremit.Transaction.senderRefId == searchTxt).ToList();

我已经加入了这两个表,但现在我的问题是我无法将它放入视图模型中以便能够将其显示到视图中,因为这两个表具有相同的列 transid 所以即使我创建了一个新模型来匹配 linq 表达式的结果值,它不会匹配,因为 transid 不能在同一视图模型中启动两次。你对我该怎么做有什么建议吗?

【问题讨论】:

    标签: asp.net-mvc entity-framework linq lambda


    【解决方案1】:

    我不确定您所说的 transid 是什么意思,不能启动两次。如果要将结果集放入 ViewModel,则需要将其放在您的选择上或查询之后:

    而不是这个:

    (transaction, remit) => new { Transaction = transaction, Remit = remit }) // selection
    

    这样做(MyViewModel 是我的视图模型的名称):

    (transaction, remit) => new MyViewModel()
    { field1 = transaction.transid, field2 = remit.whateverfield, field3 = transaction.whateverfield }) 
    //selection, replace field1 with your correct fields
    

    然后进行过滤(去掉Transaction这个词):

    .Where(transactremit => transactremit.senderRefId == searchTxt).ToList();
    

    【讨论】:

    • 很高兴听到这个消息:)
    猜你喜欢
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多