Include method for one to many relationships in EF Core

Поделиться
HTML-код
  • Опубликовано: 12 сен 2024

Комментарии • 6

  • @10Totti
    @10Totti 6 месяцев назад +1

    Nice tutorial!

  • @alfonsdeda8912
    @alfonsdeda8912 5 месяцев назад

    Great video!
    I have one question:
    Why if I do a query like this in one to many relationship doesn't throw exception in ef core but with linq to object throws:
    Suppose I have one object with many serial numbers, because the current serial number is only the last but the table is the historical too,and I want to filter what object has the serial number but only among the most recent of every object, so I did a query like this:
    Context.Objects.Include(o=> o.SerialNumbers.Where(s=> s.TypeId==2)).Where(s=> s.SerialNumbers.OrderByDescending(s=>s.Date).FirstOrDefault().Value == passed serial number). FirstOrDefault()
    I did an include with condition, but in the where clause I expected that the FirstOrDefault().Value throws exception where the FirstOrDefault () results null, but in ef core this doesn't happen.
    There is a explanation to this?
    Sorry for my english and my long question, I hope it is clear what I meant to do.
    Thanks in advance.

    • @RoundTheCode
      @RoundTheCode  4 месяца назад

      Glad you like the content.
      Your query is too complex for EF Core. For this, you are best to put it in a SQL view, then query it using the DbContext.
      Watch this video to find out how to use EF Core with views
      ruclips.net/video/TMiOAECdodM/видео.html

    • @alfonsdeda8912
      @alfonsdeda8912 4 месяца назад

      @@RoundTheCode You misunderstood my question I think.
      The query is working correctly but I don't understand why the FirstOrDefault().Value in the where clause doesn't throw exception with ef core.

    • @RoundTheCode
      @RoundTheCode  4 месяца назад

      Yes I did misunderstand.
      Are you using SQL Server to query this? If so, this article may help.
      learn.microsoft.com/en-us/ef/core/querying/null-comparisons
      When trying to match a null value in a SQL Server query, it doesn't throw an exception. When LINQ translates the query to SQL, I wonder if it does the same?