IEnumerable vs IQueryable

后端 未结 4 1674
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 15:30

I have a query:

topics.OrderBy(x => x.Replies.Any() ? x.Replies.OrderBy(y => y.PostedDate).Last().PostedDate : x.PostedDate);

It sorts th

相关标签:
4条回答
  • 2021-01-23 16:14

    Have you tried topics.OrderBy(x => x.Replies.Any() ? x.Replies.Max(y => y.PostedDate) : x.PostedDate);?

    0 讨论(0)
  • 2021-01-23 16:22

    I think EF is unable to translate your query correctly, it happens. Because it is not necessary that every lamda will convert successfully into esql, it has its own limitations. I think it is very complicated SQL query for what you are looking for.

    I will suggest you can create a new DateTime field in your topics called "LastUpdate", which will be defaulted to Topic's PostDate when it will be created. Second when you add a new reply, you make sure you update Topic's LastUpdate as well.

    By doing this, you also make your query very simple, and you avoid joining unnecessary while creating your query. You don't need to look for PostDate of replies table with any join.

    I do this kind of Caching (which is called denormalization in database design terms), this is not perfect in terms of design but by performance and coding, its much easier and simpler.

    0 讨论(0)
  • 2021-01-23 16:35

    Is you context to the database still active when you try to run the code you posted? If you (or .NET) have disposed the database context you will no longer be able to access the data in the IQueryable object because the connection is lost.

    /Viktor

    0 讨论(0)
  • 2021-01-23 16:36

    IEnumerable : LINQ to Object and LINQ to XML.

    IQueryable : LINQ to SQL

    0 讨论(0)
提交回复
热议问题