Entity Framework Include OrderBy random generates duplicate data

后端 未结 6 594
[愿得一人]
[愿得一人] 2020-11-30 02:29

When I retrieve a list of items from a database including some children (via .Include), and order the randomly, EF gives me an unexpected result.. I creates/clones addition

6条回答
  •  遥遥无期
    2020-11-30 02:50

    When you define a query path to define the query results, (use Include), the query path is only valid on the returned instance of ObjectQuery. Other instances of ObjectQuery and the object context itself are not affected. This functionality lets you chain multiple "Includes" for eager loading.

    Therefor, Your statement translates into

    from person in db.Persons.Include(p => p.Addresses).OrderBy(p => Guid.NewGuid())
    select person
    

    instead of what you intended.

    from person in db.Persons.Include(p => p.Addresses)
    select person
    .OrderBy(p => Guid.NewGuid())
    

    Hence your second workaround works fine :)

    Reference: Loading Related Objects While Querying A Conceptual Model in Entity Framework - http://msdn.microsoft.com/en-us/library/bb896272.aspx

提交回复
热议问题