Calculated column in EF Code First

后端 未结 7 1407
半阙折子戏
半阙折子戏 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 05:49

    One way is doing it with LINQ:

    var userID = 1; // your ID
    var income = dataContext.Income.First(i => i.UserID == userID);
    var outcome = dataContext.Outcome.First(o => o.UserID == userID);
    var summ = income.inSumm - outcome.outSumm;
    

    You may do it within your POCO object public class FirstTable, but I would not suggest to, because I think it's not good design.

    Another way would be using a SQL view. You can read a view like a table with Entity Framework. And within the view code, you may do calculations or whatever you want. Just create a view like

    -- not tested
    SELECT FirstTable.UserID, Income.inCome - Outcome.outCome
      FROM FirstTable INNER JOIN Income
               ON FirstTable.UserID = Income.UserID
           INNER JOIN Outcome
               ON FirstTable.UserID = Outcome.UserID
    

提交回复
热议问题