【问题标题】:Query returning wrong value?查询返回错误值?
【发布时间】:2017-09-08 00:54:18
【问题描述】:

感谢 write a query that applies to an entire db instead of a tablezambonee 提供的帮助

使用 EF 我正在编写一个从 aspNet_Users 表中返回 userId 的查询。然后我使用此 ID 删除成员资格、userINroles 和用户中的记录....但是查询返回的 userId 是错误的值..我连接到正确的数据库 iv 检查了 connectionString 并测试了其他数据

    using (DEntities Context = DAOHelper.GetObjectContext<DEntities>())
{
Guid aspUserIdToRemove = Context.ExecuteStoreQuery<string>("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 在应返回 {31E62355-8AE2-4C44-A270-2F185581B742} 时返回 {296afbff-1b0b-3ff5-9d6c-4e7e599f8b57}...

{296afbff-1b0b-3ff5-9d6c-4e7e599f8b57} 甚至在数据库中都不存在...有谁知道出了什么问题?谢谢

只是为了强调我在同一个数据库上对不同表执行进一步删除命令并确认它们已被删除

从cmets开始-

var s = dnnEntitiesDbContext.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'");

s.elementtype.GUID 包含 296afbff-1b0b-3ff5-9d6c-4e7e599f8b57

但是 s.base.elementType.baseType.Guid 返回一个差异 GUID '81c5f.... 但没有我正在寻找的那个人的迹象

【问题讨论】:

  • 澄清一下 - 从控制台运行时,语句“Select UserId FROM aspnet_Users where UserName LIKE '%” + userName + "%'" 是否返回正确的 GUID?
  • 是的,当我在 SQL 中运行 Select UserId FROM aspnet_Users where UserName LIKE '%JimBob%' 时,它返回 31E62355-8AE2-4C44-A270-2F185581B742
  • 您错误地使用了 EF - 您应该避免使用 ExecuteStoreQuery 并改用基于模型的强类型 API,如果您绝对必须使用 ExecuteStoreQuery,那么 使用参数化查询! - 您的代码容易受到 SQL 注入攻击。
  • 是否可以将 GUID 保留为字符串值,而不是尝试将其转换为 Guid 类型(然后将其转换回字符串)?我想知道 SQL 和 C# 之间的字符串和 GUID 之间的转换是否存在问题。
  • @Dai 我正在处理由另一个用户创建的现有代码我正在尝试修复错误...

标签: c# sql


【解决方案1】:

你可能对ExecuteStoreQuery&lt;T&gt;有一些误解,它会返回你指定的Type。在您的情况下,它将返回 string

Guid aspUserIdToRemove = Context.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'").ElementType.GUID;

有了这个语句,ExecuteStoreQuery&lt;string&gt; 将返回一个string 类型的UserId,然后从ElementType 获得GUID,但不是用户的GUID p>

要解决这个问题,你只需要使用

string aspUserIdToRemove = Context.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName LIKE '%" + userName + "%'");

你可能希望避免 SQL 注入更好,并使用参数

string aspUserIdToRemove = Context.ExecuteStoreQuery<string>("Select UserId FROM aspnet_Users where UserName LIKE '%{0}%'", userName);

详情可以查看API

由于aspUserIdToRemove 是一个字符串,因此您不需要在其上使用.ToString()。但是,我没有足够的数据,您可能需要检查是否需要转义“{}”。

此外,从您的评论来看,\ 是一个转义字符,如果您想在字符串中连接,您需要使用\\ (API) 对其进行转义

【讨论】:

    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多