首页 > 解决方案 > 如何使用 lambda 表达式连接表

问题描述

我是 lambda 表达式和实体框架的新手。我的问题是,我有以下表格结构。

tbl_loan => loanID,LoanValue,LoanType

tbl_crin => crID,CRValue,CUSName,FacID// 这里FacID是外键tbl_loan(loanID)

tbl_crg => crgID,crgName,CRValue,Amount FacID// 这里的FacID外键tbl_loan(loanID)

我需要编写基于loanID.how to write query using lambda expression 来获取每个表的所有列。

在这种方法中,我需要返回该查询的结果。它接受名为loanID 的参数。我尝试了一个简单的,但我不知道要写完整的代码(lambda 表达式)

public List<tbl_loan> GetCRGDetails(int loanID)
    {

        var result = new List<tbl_loan>();
        var entities = new LAEntities();
        try
        {
            result = entities.tbl_loan.Where(ln => ln.loanID == loanID).ToList();

        }
        catch (Exception e)
        {
            Logger.LogWriter("SITS.SB.LA.BL.App", e, "AgeDataLogic", "GetCRGDetails");
        }

        return result;
    }

请帮我解决这个问题。在这里我返回tbl_loan。我是否需要创建额外的类来重新调整所有数据?或有其他方法吗?

更新:

在我的项目中,部分 details.cshtml 如下,

@model SITS.SB.LA.DA.tbl_loan 

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Customer Loan Details</h4>
    <hr/>

    <label for="colFormLabelSm" class="col-sm-2 col-form-label col-form-label-sm" ng-model="">@Html.DisplayFor(model => model.ID)</label>
    <label for="colFormLabelSm" class="col-sm-2 col-form-label col-form-label-sm" ng-model="">@Html.DisplayFor(model => model.NETINCOME)</label>

那么,如何显示其他表的列值,例如 (crID,CRValue,CUSName)

我的控制器类如下,

public ActionResult Details(int id)
{
    var logic = new LoanDetailsDataLogic();
    var result = logic.GetCRGDetails(id);
    return View(result);

}

标签: c#asp.net-mvcentity-frameworklambda

解决方案


你可以试试 Include Keyword of Entity Framework like。

result = entities.tbl_loan.Include("tbl_crin").Where(ln => ln.loanID == loanID).ToList();

或者您可以编写查询,例如

 result =(from u in tbl_loan
   join t1 in tbl_crin on u.loanID = t1.loanID
   Join t2 in tbl_crg  on u.loanID = t2.loanID
   select new {u,t1,t2});

推荐阅读