[英]SQL Server ADO.NET Query conversion to Linq in WCF service
我正在嘗試將SQL查詢轉換為linq查詢,但是當我運行查詢時,它沒有返回預期的結果。 ado.net的某些代碼轉換為linq有點復雜。
這是我的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;
}
}
這是到目前為止我已經完成的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;
}
}
帶有..?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]]"}
為了達到我的期望,我必須進行哪些更改?
這是數據庫截圖:
使用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;
}
}
我注意到與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;
}
上面的邏輯不執行您認為的操作。
例如:
attamp
永遠不會為null
cheekenrty
永遠不會是您期望的int
cheekenrty.Equals(RetryAttempts)
始終為false
我懷疑您想執行以下操作:
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.