我想问一下如何在控制器中写linq以求和并在子表“”处添加到视图
我的模特1
public class ChartAccount
{
[Key]
public int ChartId { get; set; }
public int Kodeakun { get; set; }
public string Namaakun { get; set; }
public int Saldo { get; set; }
public virtual ICollection<Transaction> Transaksilist { get; set; }
}
模型2
public class Transaction
{ [Key]
public int Id { get; set; }
public string NoBukti { get; set; }
public DateTime Tanggal { get; set; }
public string Deskripsi { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
public long Debit { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
public long Credit{ get; set; }
public int? ChartId { get; set; }
public ChartAccount Transactions { get; set; }
}
我还想用借方和kredit中的值填充表saldo
在Chartaccount视图(索引)中(我在迁移时填充了初始值)
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Kodeakun)
</td>
<td>
@Html.DisplayFor(modelItem => item.Namaakun)
</td>
<td>
@Html.DisplayFor(modelItem => item.Saldo)
</td>
它是这样生成的
|Kodeakun|Namaakun |Saldo|
|10000 |Asset |0 |
|20000 |Utang |0 |
|30000 |Modal |0 |
|40000 |Pendapatan|0 |
在交易视图(索引)中
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Transactions.Kodeakun)
</td>
<td>
@Html.DisplayFor(modelItem => item.Deskripsi)
</td>
<td>
@Html.DisplayFor(modelItem => item.Debit)
</td>
<td>
@Html.DisplayFor(modelItem => item.Credit)
</td>
它是这样生成的
|Kodeakun|Debit |Credit |Deskripsi|
|10000 |1.000.000 |0 |Kas |
|20000 |0 |1.000.000|Utang |
我想在控制器中编写linq。我想在chartaccount控制器的索引或明细中写什么方法?
// GET: ChartAccounts
public async Task<IActionResult> Index()
{
return View(await _context.Accounts.ToListAsync());
}
// GET: ChartAccounts/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var chartAccount = await _context.Accounts
.FirstOrDefaultAsync(m => m.ChartId == id);
if (chartAccount == null)
{
return NotFound();
}
return View(chartAccount);
}
我尝试过,但我有点不明白如何通过查看
我在控制器详细信息中尝试的代码
//public DbSet<Transaction> Transaksi { get; set; }
//public DbSet<ChartAccount> Accounts { get; set; }
var a = from s in _context.Transaksi
group s by s.Transactions.Kodeakun;
所以基本上我想在事务中插入数据并保存。我还希望它在示例中更新数据chartaccount
|Kodeakun|Debit |Credit |Deskripsi|
|10000 |1.000.000 |0 |Kas |
|20000 |0 |1.000.000|Utang |
|10000 |0 |1.000.000|Kas |
|10000 |1.000.000 |0 |Kas |
它有借方kredit。所以我的图表帐户应该是这样
|Kodeakun|Namaakun |Saldo |
|10000 |Asset |1.000.000|
|20000 |Utang |1.000.000|
|30000 |Modal |0 |
|40000 |Pendapatan|0 |
基本上借方是(+),而Kredit是(-),所以我插入了2个Kas,分别在借方和kredit中,结果saldo为1.000.000(2.000.000-1.000.000)
对不起,我的英语
答案 0 :(得分:1)
您必须将GroupBy
与sum一起使用并构造一个新对象:
data.GroupBy(el => el.Kodeakun).Select(group => new ChartAccount
{
Saldo = group.Sum(item => item.Debit) - group.Sum(item => item.Credit),
Kodeakun = group.Key,
Namaakun = // take it from appropriate field
});