在EF 6.0中使用Sql View

时间:2015-03-28 17:32:01

标签: c# sql-server entity-framework

我有一个CashFlowView:

    CREATE VIEW [dbo].[CashFlowView]
AS
WITH CTE AS
(
SELECT 
         ROW_NUMBER() OVER (ORDER BY RateDate) AS ID
         , SUM(CASE WHEN C.CurrencyName = 'Br' THEN T.AmountMoney ELSE 0 END)  AS AmountBYR
         , SUM(CASE WHEN C.CurrencyName = 'Usd' THEN T.AmountMoney ELSE 0 END)  AS AmountUSD         
         , CR.RateDate AS [DATE]
FROM     Transactions AS T
         INNER JOIN Accounts AS A ON A.AccountID = T.CurrentAccountID
         INNER JOIN Currencies AS C ON C.CurrencyID = A.CurrencyID
         RIGHT OUTER JOIN CurrencyRates AS CR ON CR.RateDate = T.ExecutionDate
GROUP BY CR.RateDate
)
SELECT 
        ID
        , A.AmountBYR
        , (SELECT SUM(B.AmountBYR) FROM CTE B WHERE B.ID<=A.ID) AS BalanceBYR
        , A.AmountUSD
        , (SELECT SUM(B.AmountUSD) FROM CTE B WHERE B.ID<=A.ID) AS BalanceUSD
        , [Date]
FROM   CTE AS A

然后我添加了实体:

public class CashFlowView
    {
        [Key]
        public int ID { get; set; }
        public decimal AmountBYR { get; set; }
        public decimal BalanceBYR { get; set; }
        public decimal AmountUSD { get; set; }
        public decimal BalanceUSD { get; set; }
        public DateTime Date { get; set; }
    }

而且,据我所知,我需要将此代码添加到我的上下文中:

public DbSet<CashFlowView> CashFlowView { get; set; }

现在我想使用我的观点:

 IList<CashFlowView> listView;
            using (var _db = new EconomicAppContext())
            {
                listView = _db.CashFlowView.ToList();

            }

但是listView是空的。我如何创建正确的映射到View(可能使用迁移)并使用它?

1 个答案:

答案 0 :(得分:0)

我做到了。尝试结合本文 http://www.paragon-inc.com/resources/blogs-posts/a-certain-point-of-view-part-1-ef-code-first 并使用Entity Framework Power Tools查找所需的结果。并检查连接。我遇到性能问题,所以要小心使用处理方法。