1

I have Entity Framework object model with inheritance.

My linq query:

Books.ItemsNoTracking.Where(o => o.Id == new Guid("2D46B66E-64CB-4C99-AF94-5C7414048ECF")).First();

Expected query:

SELECT * FROM  [dbo].[Books] AS [Extent1] 
WHERE cast('2d46b66e-64cb-4c99-af94-5c7414048ecf' as uniqueidentifier) = [Extent1].[Id]

But EF generate:

SELECT 
    [Limit1].[C1] AS [C1], 
    [Limit1].[Id] AS [Id], 
    [Limit1].[Created] AS [Created], 
    [Limit1].[OwnerId] AS [OwnerId], 
    [Limit1].[Deleted] AS [Deleted], 
    [Limit1].[PhysicalUnitId] AS [PhysicalObjectId]
    FROM ( SELECT TOP (1) 
        [Extent1].[Id] AS [Id], 
        [Extent1].[PhysicalObjectId] AS [PhysicalObjectId], 
        [Extent2].[Created] AS [Created], 
        [Extent2].[OwnerId] AS [OwnerId], 
        [Extent2].[Deleted] AS [Deleted], 
        '0X0X' AS [C1]
        FROM  [dbo].[Books] AS [Extent1]
        INNER JOIN [dbo].[Objects] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
        WHERE cast('2d46b66e-64cb-4c99-af94-5c7414048ecf' as uniqueidentifier) = [Extent1].[Id]
    )  AS [Limit1]

It's most simple example. Other queries are too big and hard to read.

Is there any way to ignore inharitance and create simple query to only one table.

1 Answer 1

1

In order to get the query that you expect, you should not use the First() extension method. That is what adds the Top 1 clause to the inner query in your example.

I'm not sure which version of Entity Framework you're running but I when I ran similar code on a database I have using EF 6 that comes with Visual Studio, it generated a simple one layer

SELECT TOP 1 <columns> FROM <table> WHERE ID = <passed in parameter>

Since you're searching against an ID field, it should be safe to assume that you expect a single result, in which case you can use either one of Single(), First() or .Take(1) to ensure you have just one record.

You can read more about these here if you wish.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.