How can I parse a string in UNIQUEIDENTIFIER?

I am writing a LINQ Entity Framework query in which I want to parse a string in UNIQUEIDENTIFIER (aka GUID) as part of a sentence WHERE:

public IEnumerable<User> Find(Guid guid)
{
    return dbContext
        .Users
        .Where(user => Guid.Parse(user.GuidText) == guid);
}

I know this is possible in SQL because I tested it:

SELECT *
FROM Users
WHERE CAST(GuidText AS UNIQUEIDENTIFIER) = @guid;

However, I did not find a way to generate the part CAST. I tried:

  • (Guid)user.GuidTextwhich generates a compiler error.
  • Convert.ToGuid(user.GuidText)but this method does not exist.
  • Guid.Parse(user.GuidText)but this causes the Entity Framework to generate an error when it translates a LINQ query.
  • new Guid(user.GuidText)but this causes the Entity Framework to generate an error when it translates a LINQ query.
  • (Guid)Convert.ChangeType(user.GuidText, typeof(Guid))but this causes the Entity Framework to generate an error when it translates a LINQ query.
  • SqlGuid.Parse(user.GuidText)but this causes the Entity Framework to generate an error when it translates a LINQ query.

How can i achieve this? I am ready to insert SQL into the code as a last resort.

+4
source share
3 answers

EF runtime GUID , , , LINQ, .

, , Entity SQL:

var objectContext = ((IObjectContextAdapter)db).ObjectContext;
var query = objectContext.CreateQuery<User>(
  "SELECT VALUE u FROM Context.Users AS u WHERE CAST(u.GuidText AS System.Guid) = @guid", 
  new ObjectParameter("guid", guid));
+1

, , GUID:

public IEnumerable<User> Find(Guid guid)
{
    var idString = guid.ToString("N");

    return dbContext
        .Users
        .Where(user => user.UserDirectoryUserId
            .Replace("{", String.Empty)
            .Replace("}", String.Empty)
            .Replace("-", String.Empty)
            .Replace(",", String.Empty)
            .Replace("0x", String.Empty)
            .ToLower()
            == idString
        );
}

, , SQL, SQL.

0

- VIEWbased User GUID- UNIQUEIDENTIFIER

SELECT ..., CAST(GuidText AS UNIQUEIDENTIFIER), ...

, ,

0
source

All Articles