2015-01-21 18 views
0

Here我學會了如何計算相關的實體,而無需加載它們。問題是我在編譯時沒有實體類型。我的情況:計數相關的實體,而無需加載它們,非通用的方式

var postCount = context.Entry(someObject) // someObject received from somewhere 
         .Collection(somePropertyString) 
         .Query()    // and here I got a non-generic IQueryable 
         .Count();    // which has no Count method 

如果我試圖.Query().Cast<object>().Count()我收到運行時異常這一行:

System.NotSupportedException發生的HResult = -2146233067
消息=無法轉換鍵入'...'鍵入 'System.Object'。 LINQ to Entities僅支持投射EDM原語 或枚舉類型。 Source = EntityFramework

那麼,如何在不加載它們的情況下計算相關實體,如果我在編譯時沒有實體類型呢?

+1

對我來說,你必須使用反射來獲取一個'表達 >>'才能夠使用Collection'的'通用版本,可以讓你使用'Count()'。 – tschmit007 2015-01-21 10:29:32

回答

1

使用反射是一種選擇。這個擴展方法幫助我:

public static int Count(this IQueryable q) 
{ 
    return (int)q.Provider.Execute(
     Expression.Call(typeof(Queryable), 
      "Count", 
      new[] { q.ElementType }, 
      new[] { q.Expression })); 
} 
0

你也可以這樣寫:

int count = context.Blogs.Single(blog=> blog.Id = yourCriteriaId).Posts.Count(); 

這也不會加載該對象。

它會產生一些像這樣的SQL語句(簡體):

Select Count(*) from Post where Post.BlogID = 3 
+0

我不知道它是一個'Blog'還是其他的東西。我編輯過的問題,這是一個有點誤導性 – astef 2015-01-21 10:00:00

+0

你必須知道,因爲在你的例子中,你認爲你的不是那麼未知的類型有'Posts'屬性。 – tschmit007 2015-01-21 10:02:43

+0

@ tschmit007它從msdn示例中複製粘貼,現在它已被更正 – astef 2015-01-21 10:03:22

相關問題