简体   繁体   English

在WCF服务中将SQL Server ADO.NET查询转换为Linq

[英]SQL Server ADO.NET Query conversion to Linq in WCF service

I am trying to convert a SQL query to linq query but when I run the query, it's not returning the expected result. 我正在尝试将SQL查询转换为linq查询,但是当我运行查询时,它没有返回预期的结果。 Some of the ado.net code is a little bit complicated to convert to linq. ado.net的某些代码转换为linq有点复杂。

Here is my ADO.NET code: 这是我的ADO.NET代码:

public bool AuthenticateUser(UserLogin userLogin)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        var result = false;

        SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
        cmd.CommandType = CommandType.StoredProcedure;

        string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");
        SqlParameter paramUsername = new SqlParameter("@UserName", userLogin.Username);
        SqlParameter paramPassword = new SqlParameter("@Password", encryptedpassword);
        cmd.Parameters.Add(paramUsername);
        cmd.Parameters.Add(paramPassword);

        con.Open();

        SqlDataReader rdr = cmd.ExecuteReader();

        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);

                if (Convert.ToBoolean(rdr["AccountLocked"]))
                {
                    result = false;
                }
                else if (RetryAttempts == 1)
                {
                    result = false;
                }
                else if (RetryAttempts > 1)
                {
                    int AttemptsLeft = (4 - RetryAttempts);
                    result = true;
                }
                else if (Convert.ToBoolean(rdr["Authenticated"]))
                {
                    result = true;
                }
            }
        }

        return result;
    }
}

Here is the linq query so far I have done .. 这是到目前为止我已经完成的linq查询..

public bool AuthenticateUser1(UserLogin userLogin)
{ 
    using (HalifaxDatabaseEntities db = new HalifaxDatabaseEntities())
    {
        var exceeded = false;
        var Totalcount = 0;
        int RetryAttempts = 4;

        var attamp = from X in db.tblUsers
                     where X.Username == userLogin.Username && X.Password == userLogin.Password
                     select X;

        if (attamp != null)
        {
            var cheekenrty = from x in db.tblUsers
                             where x.RetryAttempts == RetryAttempts
                             select x;

            if (cheekenrty.Equals(RetryAttempts))
            {
                return exceeded;
            }
            else
            {
                return true;
            }
        }
        else
        {
           Totalcount++;
        }

        return exceeded;
    }
}

Imidate windows out put with .. ?cheekenrty.GetType() 带有..?cheekenrty.GetType()的仿窗

?cheekenrty.GetType()
{Name = "DbQuery`1" FullName = "System.Data.Entity.Infrastructure.DbQuery`1[[HalifaxWCFProject.tblUser, HalifaxWCFProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}
    Assembly: {EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089}
    AssemblyQualifiedName: "System.Data.Entity.Infrastructure.DbQuery`1[[HalifaxWCFProject.tblUser, HalifaxWCFProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
    Attributes: Public | BeforeFieldInit
    BaseType: {Name = "Object" FullName = "System.Object"}
    ContainsGenericParameters: false
    CustomAttributes: Count = 2
    DeclaredConstructors: {System.Reflection.ConstructorInfo[1]}
    DeclaredEvents: {System.Reflection.EventInfo[0]}
    DeclaredFields: {System.Reflection.FieldInfo[2]}
    DeclaredMembers: {System.Reflection.MemberInfo[33]}
    DeclaredMethods: {System.Reflection.MethodInfo[23]}
    DeclaredNestedTypes: {System.Reflection.TypeInfo.<get_DeclaredNestedTypes>d__23}
    DeclaredProperties: {System.Reflection.PropertyInfo[7]}
    DeclaringMethod: '((System.RuntimeType)cheekenrty.GetType()).DeclaringMethod' threw an exception of type 'System.InvalidOperationException'
    DeclaringType: null
    FullName: "System.Data.Entity.Infrastructure.DbQuery`1[[HalifaxWCFProject.tblUser, HalifaxWCFProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"
    GUID: {c4b5504f-41cb-377c-9215-465d09961eab}
    GenericParameterAttributes: '((System.RuntimeType)cheekenrty.GetType()).GenericParameterAttributes' threw an exception of type 'System.InvalidOperationException'
    GenericParameterPosition: '((System.RuntimeType)cheekenrty.GetType()).GenericParameterPosition' threw an exception of type 'System.InvalidOperationException'
    GenericTypeArguments: {System.Type[1]}
    GenericTypeParameters: {System.Type[0]}
    HasElementType: false
    ImplementedInterfaces: {System.Type[10]}
    IsAbstract: false
    IsAnsiClass: true
    IsArray: false
    IsAutoClass: false
    IsAutoLayout: true
    IsByRef: false
    IsCOMObject: false
    IsClass: true
    IsConstructedGenericType: true
    IsContextful: false
    IsEnum: false
    IsExplicitLayout: false
    IsGenericParameter: false
    IsGenericType: true
    IsGenericTypeDefinition: false
    IsImport: false
    IsInterface: false
    IsLayoutSequential: false
    IsMarshalByRef: false
    IsNested: false
    IsNestedAssembly: false
    IsNestedFamANDAssem: false
    IsNestedFamORAssem: false
    IsNestedFamily: false
    IsNestedPrivate: false
    IsNestedPublic: false
    IsNotPublic: false
    IsPointer: false
    IsPrimitive: false
    IsPublic: true
    IsSealed: false
    IsSecurityCritical: true
    IsSecuritySafeCritical: false
    IsSecurityTransparent: false
    IsSerializable: false
    IsSpecialName: false
    IsUnicodeClass: false
    IsValueType: false
    IsVisible: true
    MemberType: TypeInfo
    MetadataToken: 33556295
    Module (System.Reflection.MemberInfo): {EntityFramework.dll}
    Module: {EntityFramework.dll}
    Name: "DbQuery`1"
    Namespace: "System.Data.Entity.Infrastructure"
    ReflectedType: null
    StructLayoutAttribute: {System.Runtime.InteropServices.StructLayoutAttribute}
    TypeHandle: {System.RuntimeTypeHandle}
    TypeInitializer: null
    UnderlyingSystemType: {Name = "DbQuery`1" FullName = "System.Data.Entity.Infrastructure.DbQuery`1[[HalifaxWCFProject.tblUser, HalifaxWCFProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"}

What are the changes I have to make to worked it according my expectation? 为了达到我的期望,我必须进行哪些更改?

Here is the database screenshot: 这是数据库截图:

单击此处查看数据库记录

Using Linq to Entities you can use .Any() inside an if and chain as many conditions you want. 使用Linq to Entities,可以在if和链内使用任意数量的条件来使用.Any()

public bool AuthenticateUser1(UserLogin userLogin)
{
    using (HalifaxDatabaseEntities db = new HalifaxDatabaseEntities())
    {
        var Totalcount = 0;
        int RetryAttempts = 4;

        if (db.tblUsers
           .Any(x => x.Username == userLogin.Username &&
                     x.Password == userLogin.Password && 
                     x.RetryAttempts <= RetryAttempts))
                    {
                        return true;
                    }

            TotalCount++;
            return false;
    }
}

I noticed that you didn't encrypt your password in your linq query unlike in your ADO.NET version. 我注意到与ADO.NET版本不同,您没有在linq查询中加密密码。

string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");

var attamp = from X in db.tblUsers
             where X.Username == userLogin.Username && X.Password == encryptedpassword 
             select X;
var attamp = from X in db.tblUsers
             where X.Username == userLogin.Username && X.Password == userLogin.Password
             select X;

if (attamp != null)
{
    var cheekenrty = from x in db.tblUsers
                     where x.RetryAttempts == RetryAttempts
                     select x;

    if (cheekenrty.Equals(RetryAttempts))
    {
        return exceeded;
    }
    else
    {
        return true;
    }

The above logic does not do what you think it does. 上面的逻辑不执行您认为的操作。

For example: 例如:

  • attamp will never be null attamp永远不会为null
  • cheekenrty will never be an int as you expected cheekenrty永远不会是您期望的int
  • cheekenrty.Equals(RetryAttempts) will always be false cheekenrty.Equals(RetryAttempts)始终为false

I suspect you want to do something like: 我怀疑您想执行以下操作:

var attamp = (from X in db.tblUsers
             where X.Username == userLogin.Username && X.Password == userLogin.Password
             select X).SingleOrDefault();

if (attamp != null)
{
    // It is also possible that >= should be < or <= - it is hard to tell what your intent is
    return attamp.RetryAttempts >= RetryAttempts;  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM