当前位置:  开发笔记 > 编程语言 > 正文

实体框架6投影生成等效于"Select*"的SQL,并且不生成WHERE子句

如何解决《实体框架6投影生成等效于"Select*"的SQL,并且不生成WHERE子句》经验,为你挑选了0个好方法。

我正在维护一个带有Entity framework 6和MSSQL服务器数据库的ASP.NET WebAPI2应用程序.IoC容器是Castle Windsor.我在我的存储库上有一个方法,用于从DB获取用户的一些详细信息.由于我不需要每一列,我以为我会使用投影.问题是生成的SQL选择了表中的所有列.这是DbContext

public partial class SecurityContext : DbContext
{
    public SecurityContext()
        : base("name=SecurityContext")
    {
    }

    public virtual DbSet secUsers { get; set; }
}

这是在存储库中声明/初始化上下文的位置

public class BaseRepository : IRepository where T : class
{
    protected DbContext context;

    public BaseRepository()
    {
        context = new SecurityContext();
    }

    public BaseRepository(DbContext context)
    {
        this.context = context;
    } 
    //elided
}

这是存储库中的方法

public User FindUserForLoginVerification(string name)
{         
    var loginInfo = context.Set()
        .Where(c => c.LoginName == name)
        .Select(c => new 
        { 
            LoginName = c.LoginName, 
            Password = c.HashedPassword, 
            Salt = c.PasswordHashSalt 
        })
        .SingleOrDefault();

    return new User() { 
        LoginName = loginInfo.LoginName, 
        HashedPassword = loginInfo.Password, 
        PasswordHashSalt = loginInfo.Salt                
    };
}

这是输出SQL.

SELECT 
[Extent1].[UserId] AS [UserId], 
[Extent1].[CreatedByUserId] AS [CreatedByUserId], 
[Extent1].[Comment] AS [Comment], 
[Extent1].[CreatedDate] AS [CreatedDate], 
[Extent1].[DefaultCulture] AS [DefaultCulture], 
[Extent1].[EmailAddress] AS [EmailAddress], 
[Extent1].[FirstName] AS [FirstName], 
[Extent1].[IsDeleted] AS [IsDeleted], 
[Extent1].[IsExcludedFromPasswordPolicy] AS [IsExcludedFromPasswordPolicy], 
[Extent1].[IsChangePassword] AS [IsChangePassword], 
[Extent1].[IsLocked] AS [IsLocked], 
[Extent1].[LastName] AS [LastName], 
[Extent1].[LastPasswordChangeDate] AS [LastPasswordChangeDate], 
[Extent1].[LoginName] AS [LoginName], 
[Extent1].[NumberOfFailedLoginAttempts] AS [NumberOfFailedLoginAttempts], 
[Extent1].[PasswordHash] AS [PasswordHash], 
[Extent1].[PasswordHashSalt] AS [PasswordHashSalt]
[Extent1].[UpdatedDate] AS [UpdatedDate]
FROM [dbo].[User] AS [Extent1]

我想我做错了什么,但我无法弄清楚是什么.任何想法将不胜感激.

编辑:我只是注意到一些奇怪的事情 - 在生成的SQL中没有WHERE子句,这意味着从数据库中选择所有行,将其带到客户端并在那里进行过滤.编辑2:使用LINQ查询语法生成相同的SQL.编辑3:在编写单元测试后,我手动实例化存储库和服务(而不是将其留给CastleWindsor),运行测试时生成的SQL具有WHERE子句.

推荐阅读
黄晓敏3023
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有