Calculated column in EF Code First

后端 未结 7 1377
半阙折子戏
半阙折子戏 2020-11-28 05:16

I need to have one column in my database calculated by database as (sum of rows) - (sum of rowsb). I\'m using code-first model to create my database.

Here is what I

相关标签:
7条回答
  • 2020-11-28 06:10

    I would go about this by just using a view model. For example rather than have the FirstTable class as a db entity would you not be better just having a view model class called FirstTable and then have a function that is used to return this class that would include the calculated sum? For example your class would just be:

    public class FirstTable {
      public int UserID { get; set; }
      public double Sum { get; set; }
     }
    

    And then you would have a function that you call that returns the calculated sum:

    public FirsTable GetNetSumByUserID(int UserId)
    {
      double income = dbcontext.Income.Where(g => g.UserID == UserId).Select(f => f.inSum);
      double expenses = dbcontext.Outcome.Where(g => g.UserID == UserId).Select(f => f.outSum);
      double sum = (income - expense);
      FirstTable _FirsTable = new FirstTable{ UserID = UserId, Sum = sum};
      return _FirstTable;
    }
    

    Basically the same as an SQL view and as @Linus mentioned I don't think it would be a good idea keeping the computed value in the database. Just some thoughts.

    0 讨论(0)
提交回复
热议问题