在ASP.NET中在2个等于列上连接2个表

时间:2019-01-18 08:38:36

标签: asp.net

请帮助我修复代码以联接2个表,但2个相等。 我有2个表格(交易和Chartaccount)

Chartaccount Table
+---------+--------+
|KodeAkun |NamaAkun|
+---------+--------+
|10000    |Asset   |
|20000    |Expense |
|30000    |Revenue |
+------------------+

Transaction Table
+---------+--------+---------+-------+
|KodeAkunD| DEBIT  |KodeAkunK|KREDIT |
+---------+--------+---------+-------+
|10000    |10000   |20000    |0      |
+------------------+---------+-------+

在我的模型中

Chartaccount Model
public string KodeAkun {get; set;}
public string NamaAkun {get; set;}
public decimal Saldo {get; set;}

Transaction Model
public string KodeAkunD {get; set;}
public string KodeAkunK {get; set;}
public decimal Debit {get; set;}
public decimal Kredit {get; set;}
public string Keterangan {get; set;}

在我的控制器中

public IActionResult Index()
{
var transaction1 = from p in _context.Transaction join k in _context.ChartAccount on p.KodeakunD equals k.Kodeakun
                           select new Transaction {
                           KodeakunD = p.KodeakunD + k.Namaakun,
                           KodeakunK = p.KodeakunK + k.Namaakun};          
return View(transaction1);
}

目前在我看来

+-----------+--------+----------+-------+-------------------+
|KodeAkunD  | DEBIT  |KodeAkunK |KREDIT |Action             |
+-----------+--------+----------+-------+-------------------+
|10000Asset |10000   |20000Asset|0      |Edit,Details,Delete|
+-----------+--------+----------+-------+-------------------+

我想要什么

+-----------+--------+------------+-------+-------------------+
|KodeAkunD  | DEBIT  |KodeAkunK   |KREDIT |Action             |
+-----------+--------+------------+-------+-------------------+
|10000Asset |10000   |20000Expense|0      |Edit,Details,Delete|
+-----------+--------+------------+-------+-------------------+

而且,如果我加入控制器,我的操作将无法正确路由,如果我单击我的操作,它将返回404

1 个答案:

答案 0 :(得分:0)

您的问题在这一行

KodeakunK = p.KodeakunK + k.Namaakun

p.KodeakunK = 2000,但是您在p.KodeakunD上连接了表,p.KodeakunD是1000的连接线,导致“资产”。

您需要分别通过Chartaccount加入KodeakunK和KodeakunD。 您可以选择两个不同的联接,也可以使用linq多个联接。

LINQ to Entity : Multiple join conditions的可能重复项

Linq multiple join conditions using extra variables

LINQ multiple joins with multiple conditions

How to do joins in LINQ on multiple fields in single join

这些可以帮助您。