Asp .net mvc 4具体的“select ....”命令

时间:2014-02-14 11:43:16

标签: c# sql-server asp.net-mvc asp.net-mvc-4

我正在努力为自己制作一个ebank,所以它并不那么严重。这是我的结构: http://i60.tinypic.com/rig0sx.png

到目前为止我取得的成就:如果用户登录,并点击Ebank动作链接,为他/她显示所有数据(我的意思是如果登录 userId == 1 我用 userId == 2 显示所有数据,这是我想要改变的。)

public ActionResult Index()
{

     var bankaccounts = db.BankAccounts.Include(b => b.Type).Include(b => b.Balance).Include(b => b.UserProfile);
     return View(bankaccounts.ToList());

}

如果我是对的,这个“var bankaccounts”行是我必须改变的。如果我将断点放到“返回视图(bankaccounts.ToList())”行,我会从“bankaccounts”中获取以下数据:

    {
SELECT 
    [Extent1].[BankAccountId] AS [BankAccountId], 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[AccountName] AS [AccountName], 
    [Extent1].[AccountType] AS [AccountType], 
    [Extent1].[AccountNumber] AS [AccountNumber], 
    [Extent1].[AccountStatus] AS [AccountStatus], 
    [Extent1].[AccountAvaiability] AS [AccountAvaiability], 
    [Extent2].[AccountType] AS [AccountType1], 
    [Extent2].[TypeName] AS [TypeName], 
    [Extent3].[BalanceId] AS [BalanceId], 
    [Extent3].[BalanceAmount] AS [BalanceAmount], 
    [Extent3].[TrustAmount] AS [TrustAmount], 
    [Extent4].[UserId] AS [UserId1], 
    [Extent4].[UserName] AS [UserName]
    FROM    [dbo].[BankAccount] AS [Extent1]
    INNER JOIN [dbo].[Type] AS [Extent2] ON [Extent1].[AccountType] = [Extent2].[AccountType]
    LEFT OUTER JOIN [dbo].[Balance] AS [Extent3] ON [Extent1].[BankAccountId] = [Extent3].[BalanceId]
    INNER JOIN [dbo].[UserProfile] AS [Extent4] ON [Extent1].[UserId] = [Extent4].[UserId]}

问题:

我在代码中找不到任何真正的sql命令(由mvc自动生成),所以如果我是对的

  1. 这个“var bankaccounts”行是否执行sql select?
  2. 如果是,怎么样?
  3. 这种编程后我在哪里可以阅读?
  4. 我想将此代码更改为“select ... where userid == websecurity.CurrentUserId”,您可以帮我解决这个问题吗?
  5. 我应该采取或阅读的更多想法,建议?你说的越多,我就能学得越多!

1 个答案:

答案 0 :(得分:1)

您正在使用像Entity Framework这样的提供程序,它提供从代码到数据库的映射。具体做法是:

  1. 在您的情况下,当您使用ToList()实现查询时,将执行Sql。在实现步骤之前,var bankaccountsIQueryable
  2. Entity Framework有一个Query提供程序,它知道如何解析你将它提供给Sql语句的表达式,同样地,将结果集映射回BankAccount之类的实体。
  3. Sites like MSDN会给你一个概述
  4. 添加Where表达式谓词:
  5. var userBankaccounts = db.BankAccounts
                             .Where(ba => ba.UserId == websecurity.CurrentUserId);
    

    你看到的Sql是'真实的'(没有卷曲的{}括号) - 一旦你看到相当讨厌的表和派生表的别名为[Extentxxx],它将允许你快速检查你的Linq表达式正在执行所需的查询。