查询返回错误的值?
感谢我从zambonee收到的帮助, 写了一个适用于整个数据库而不是表的查询
使用EF我正在编写一个从aspNet_Users表返回userId的查询。 然后我使用此ID删除成员资格,userINroles和用户中的记录….但是查询返回的userId是错误的值..并且我连接到正确的数据库iv检查了connectionString并测试了其他数据
using (DEntities Context = DAOHelper.GetObjectContext()) { Guid aspUserIdToRemove = Context.ExecuteStoreQuery("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'").ElementType.GUID; string aspUserId = aspUserIdToRemove.ToString(); aspUserId = aspUserId.Replace("{", string.Empty); aspUserId = aspUserId.Replace("}", string.Empty); Context .ExecuteStoreCommand("DELETE FROM aspnet_Membership where UserId = '" + aspUserId + "'"); Context .ExecuteStoreCommand("DELETE FROM aspnet_UsersInRoles where UserId = '" + aspUserId + "'"); Context .ExecuteStoreCommand("DELETE FROM aspnet_Users where UserId = '" + aspUserId + "'");
aspUserIdToRemove返回{296afbff-1b0b-3ff5-9d6c-4e7e599f8b57}时应返回{31E62355-8AE2-4C44-A270-2F185581B742} …
{296afbff-1b0b-3ff5-9d6c-4e7e599f8b57}甚至不存在于DB中……有没有人知道什么是错的? 谢谢
只是为了强化在同一个数据库上进行进一步删除不同表上的命令并确认它们已被删除
继评论之后 –
var s = dnnEntitiesDbContext.ExecuteStoreQuery("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'");
s.elementtype.GUID持有296afbff-1b0b-3ff5-9d6c-4e7e599f8b57
但s.base.elementType.baseType.Guid返回差异GUID’81c5f ….但没有我正在寻找的那个迹象
您可能对ExecuteStoreQuery
有一些误解,它将返回您指定的Type
。 在您的情况下,它将返回string
。
Guid aspUserIdToRemove = Context.ExecuteStoreQuery("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'").ElementType.GUID;
使用此语句, ExecuteStoreQuery
将返回string
类型UserId
,然后从ElementType
获取GUID
,但不获取用户的 GUID
要解决这个问题,您只需要使用即可
string aspUserIdToRemove = Context.ExecuteStoreQuery("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'");
更好的是,您可能希望避免SQL注入,并使用参数
string aspUserIdToRemove = Context.ExecuteStoreQuery("Select UserId FROM aspnet_Users where UserName LIKE '%{0}%'", userName);
您可以查看API的详细信息
由于aspUserIdToRemove
是一个字符串,因此您不需要使用.ToString()
。 但是,我没有足够的数据,您可能需要检查是否需要转义'{}’。
而且,从你的注释中, \
是一个转义字符,如果你想在一个字符串中连接,你需要用\\
( API )来转义它