kriss kriss -4 years ago 120
C# Question

Linq query - get first object of related entity

I have a problem with my query

var ninjas = from n in this.dbContext.Ninjas
join e in this.dbContext.Equipment on n.Id equals e.NinjaId
select ( new NinjaModel()
Id = n.Id,
Name = n.Name,
FirstEquipmentItemName = n.Equipment.FirstOrDefault()?.Name,
BornDate = DbFunctions.TruncateTime(n.BornDate).Value

I cant use FirstOrDefault in my query and I want to get first item name of ninja equipment there. Is it possible? I know I can use


but then DbFunctions.TruncateTime wont work.

Answer Source

Your problems is usage of null-conditional operator in query:

FirstEquipmentItemName = n.Equipment.FirstOrDefault()?.Name

That will give an error

An expression tree lambda may not contain a null propagating operator.

What you need - just get name without null-conditional operator. In case if there is no related entites, name will have null value:

FirstEquipmentItemName = n.Equipment.FirstOrDefault().Name

What is happening behind the scene - EF generates SQL query which returns TOP (1) equipment name from related table. Something like:

    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name],
    (SELECT TOP (1)
        [Extent2].[Name] AS [Name]
        FROM [dbo].[Equipment] AS [Extent2]
        WHERE [Extent1].[Id] = [Extent2].[Id]) AS [C1]
    FROM [dbo].[Ninjas] AS [Extent1]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download