LINQ To Entities request: as returns null, you can use it regardless

This is probably the same with LINQ To SQL.

I did a beginner mistake (see this thread).

Indeed, shlomiw uses (b as Derived1).Prop_d1 even if b is not of type Derived1 (and so (b as Derived1) can be nul).

And it’s ok! (no exception)

Why? In fact it’s easy. The as is translated from LINQ To Entities request to SQL request.

Take the two EDM inheritance cases:

Imagine we have two tables:

For the TPT case:

The SQL generated request from LINQ To Entities request:

from t in context.TestNull1

select (t as TPTTestNull2).Test2


is:

SELECT
CASE WHEN (CASE WHEN ( NOT (([Project1].[C1] = 1) AND ([Project1].[C1] IS NOT NULL))) THEN ’0X’ ELSE ’0X0X’ END LIKE ’0X0X%’) THEN [Extent1].[Test2] END AS [C1]
FROM  [dbo].[TestNull1] AS [Extent1]
LEFT OUTER JOIN  (SELECT
 [Extent2].[Id] AS [Id],
 cast(1 as bit) AS [C1]
 FROM [dbo].[TestNull2] AS [Extent2] ) AS [Project1] ON [Extent1].[Id] = [Project1].[Id]

 

For TPH case:

The SQL generated request from LINQ To Entities request:

from t in context.TestNull1

select (t as TPHDerived).Test2


is:


SELECT
CASE WHEN (CASE WHEN ((CASE WHEN ([Extent1].[Dicriminator] IS NOT NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END) <> cast(1 as bit)) THEN ’0X’ ELSE ’0X0X’ END LIKE ’0X0X%’) THEN [Extent1].[Test2] END AS [C1]
FROM [dbo].[TestNull1] AS [Extent1]

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>