这是两个表,
amounttbl, amountId - amountValue
requesttbl reqId - reqAmount - Rate - soldAmount, amountId
数据:
amounttbl
amountId | amountValue
---------|------------
1 | 5000
requesttbl
reqId | reqAmount | Rate | soldAmount | amountId
------|-----------|------|------------|---------
1| 2000| 12| 0| 1
2| 500| 12| 0| 1
3| 1000| 11| 0| 1
4| 500| 10| 0| 1
5| 1000| 10| 0| 1
为此,我准备了一个行动,应该从高利率到低利率卖出5000,这里它将从(1-2-3)卖出总数将是4500,它将保持500。现在应该分发(4& 5)。首先,它应该为:
4--500/1500 = 0.33,5至1000/1500 = 0.66
4将获得500%的0.33%,5将获得500%的0.66%。
为此,我创建了一个动作,但它有一些问题:
id = 1;
amount = 5000;
var requests = db.request.Where(a => a.amountId== id).OrderBy(a => a.Rate);
foreach(var item in requests)
{
decimal soldamount = db.request.Where(a => a.amountId== id).Sum(a => a.reqAmount);
decimal available= amount - soldamount ;
while (available>= item.reqAmount)
{
item.soldAmount= item.reqAmount;
}
}
db.SaveChanges();
我在这里遇到两个问题,一个问题在foreach
:
已经有一个与此命令关联的开放DataReader 必须先关闭。
这是因为:
decimal soldamount = db.request.Where(a => a.amountId == id).Sum(a => a.reqAmount);
而且我不知道如何计算记录4,5,并确定他们的作用。
答案 0 :(得分:0)
嗯,说实话,我没有得到你的算法,但至于open DataReader
问题,试试这段代码:
id = 1;
amount = 5000;
//Get list of objects from db (assuming db is `DbContext` and request is `IDbSet` stuff)
var requests = db.request.Where(a => a.amountId== id).OrderBy(a => a.Rate).ToList();
//we already have requests with amountId == id in *requests* variable above.
//db.request.Where(a => a.amountId== id).Sum(a => a.reqAmount);
//This does not change during loop, so calculate before hand
var soldamount = requests.Sum(a => a.reqAmount);
decimal available = amount - soldamount;
foreach(var item in requests)
{
//don't get concept of while here as you are not changing either
//item.reqAmount not available
if(available>= item.reqAmount)
{
item.soldAmount= item.reqAmount;
}
}
db.SaveChanges();