简体   繁体   中英

Linq to EF guid in where clause always returns null

I've tried many different ways and the "topic" is always null from the LINQ statement. Is there something special that has to be done when comparing GUIDs with SQLite as the data source?

    public TopicModel GetTopicModel(Guid id)
    {
        TopicModel topicModel = null;
        using (var context = new onenessEntities())
        {
            var topic = context.Topics.FirstOrDefault(x => x.Id.Equals(id));

            if (topic != null)
            {
                topicModel = new TopicModel
                {
                    Id = topic.Id,
                    Description = topic.Description,
                    Title = topic.Title
                };
            }
        }

        return topicModel;
    }

Auto Generated SQL

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[CategoryId] AS [CategoryId], 
[Extent1].[Language] AS [Language], 
[Extent1].[Title] AS [Title], 
[Extent1].[Description] AS [Description], 
[Extent1].[Keywords] AS [Keywords], 
[Extent1].[Version] AS [Version], 
[Extent1].[CurrentPosition] AS [CurrentPosition], 
[Extent1].[Notes] AS [Notes]
FROM [Topic] AS [Extent1]
WHERE ([Extent1].[Id] = @p__linq__0) AND (@p__linq__0 IS NOT NULL) LIMIT 1


-- p__linq__0: '90f8f2c6-31cf-47a1-b8fb-61d5f4130d8f' (Type = AnsiStringFixedLength)

-- Executing at 9/17/2015 2:56:37 PM -05:00

-- Completed in 1 ms with result: SQLiteDataReader

Edit : I've learned this issue is due to SQLite storing GUIDs as binary blobs. As a work around I changed the data type from GUID to CHAR(36) and now am able to use LINQ to EF to retrieve the records. I'd still like to see if someone can answer this original question though.

To fix this issue append this to the connection string:

;binaryguid=False

If true - GUID columns are stored in binary form; otherwise GUID columns are stored as text. I think the issue otherwise caused by the way EF injects the parameter (Type = AnsiStringFixedLength).

Queries using guid parameters will still work fine with binaryguid when using a raw query (SQLiteCommand with execute reader). Avoiding EF lets you supply your own.

command.Parameters.Add(new SQLiteParameter(DbType.Guid)
{
    ParameterName = "@id",
    Value = id
});

我将Id的数据类型更改为CHAR而不是GUID,以解决此问题。

I wonder what SQL is being generated for the where clause x => x.Id.Equals(id) ? I found this link which discusses a bug in the Expression Analyzer if id happens to be a nullable uniqueidentifier.

The suggested fix was to use Equals in this manner instead: x => Object.Equals(x.Id, id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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