如何根据EntityFramework中的另一个表更新表?

时间:2017-07-10 05:55:30

标签: c# entity-framework linq tsql

我有这个数据的StationStateItem表:

Id  SSHdrRef      Amount  
---------------------------
1   1(forrein Key)   1
2   1                1
3   2                2
4   2                2
5   3                1

我希望在StationStateHdr中更改金额时更新StationStateItem表。

BeforeSSAmount=StationStateHdr.StationStateItem.Sum(x=> x.Amount)

StationStateHdr表格如下:

Id  BeforeSSAmount
--------------
1   0 
2   2 (1+1)
3   6 (1+1+2+2)

2 个答案:

答案 0 :(得分:2)

尝试代码

  foreach(var a in StationStateHdr)
   {
     a .BeforeSSAmount=StationStateHdr.StationStateItem.where(c=>c.SSHdrRef<a.id).Sum(x=> x.Amount)
   }

答案 1 :(得分:1)

试试这段代码:

var afters = ctx.headers.SkipWhile(((x, index) => index <= currentItemIndex))
                .TakeWhile((x, index) => index != ctx.headers.Count()-1).ToList();

            for (int i = currentItemIndex+1, j=0; j < afters.Count; i++ ,j++)
            {
                var befores = ctx.headers.TakeWhile((x, index) => index <i);
                afters[j].BeforeSSAmount = befores.SelectMany(x => x.StationStateItem).Sum(x => x.Amount);
            }

在wpf:

中编辑使用ListCollectionView
  var afters = header.DataSource.Cast<StationStateHdr>().SkipWhile(((x, index) => index <= header.DataSource.CurrentPosition))
        .TakeWhile((x, index) => index != header.DataSource.Cast<StationStateHdr>().Count()-1).ToList();

    for (int i = header.DataSource.CurrentPosition+1, j=0; j < afters.Count; i++ ,j++)
    {
        var befores = header.DataSource.Cast<StationStateHdr>().TakeWhile((x, index) => index <i);
        afters[j].BeforeSSAmount = befores.SelectMany(x => x.StationStateItem).Sum(x => x.Amount);
    }

或本代码:

    var listOfStationStateHdr = header.DataSource.Cast<StationStateHdr>();
    listOfStationStateHdr.SkipWhile(((x, index) => index <= header.DataSource.CurrentPosition))
        .TakeWhile((x, index) => index != header.DataSource.Cast<StationStateHdr>().Count() - 1).ToList().ForEach(x =>
    {
        x.BeforeSSAmount = listOfStationStateHdr.TakeWhile(y => y.Id < x.Id).SelectMany(b => b.StationStateItem).Sum(s => s.Amount);
    });

    var sumCurrent = CurrentStationStateHdr.StationStateItem.Sum(t => t.Amount);
    var listOfStationStateHdr = header.DataSource.Cast<StationStateHdr>().ToList();
    double? nextItembeforeSSAmount = listOfStationStateHdr[header.DataSource.CurrentPosition + 1].BeforeSSAmount;

    listOfStationStateHdr.SkipWhile(((x, index) => index <= header.DataSource.CurrentPosition))
        .TakeWhile((x, index) => index != header.DataSource.Cast<StationStateHdr>().Count() - 1).ToList().ForEach(x =>
        {
            x.BeforeSSAmount += sumCurrent - nextItembeforeSSAmount;
        });
相关问题