2015-02-06 80 views
0

我需要根據元組值列表返回一組MyClass。這個元組值用於從數據庫中獲取正確的對象。 爲了避免多次調用db,我試圖使用Union來構建查詢,然後只需調用.ToList()方法即可從db獲取所有數據。 在這種情況下,如果查詢中沒有結果,我需要返回一個默認值對象。當我應用DefaultIfEmpty方法時,出現錯誤。這個想法是,如果我收到15個元組的List,我需要返回15個結果,如果沒有結果,它們應該填充內置的默認值Class值。使用DefaultIfEmpty在使用Union時獲取默認類值

public ISet<MyClass> Post([FromBody] IList<Tuple<string, string>> codesToFilter) 
{ 
    IEnumerable<MyClass> filteredObjectsByCodes = new List<MyClass>(); 

    foreach (Tuple<string, string> tupleElement in codesToFilter) 
    { 
     //Class built based on parameters to be returned if there are no records in db 
     MyClass classDefaultValue = new MyClass(tupleElement.Item1, 
      "A default property string", 
      "Default text", 
      tupleElement.Item2); 

     var filteredObjects = (from entity in DatabaseContext.MyEntities 
           where (entity.Property1 == tupleElement.Item1 && 
            entity.Property4== tupleElement.Item2) 
           select new MyClass 
           (
            entity.Property1, 
            entity.Property2, 
            entity.Property3, 
            entity.Property4 
           ) 
          ).DefaultIfEmpty(classDefaultValue); 

     filteredObjectsByCodes = filteredObjectsByCodes.Union(filteredObjects); 
    } 

    var filteredObjectsResult = new HashSet<MyClass>((filteredObjectsByCodes.ToList())); 

    return filteredObjectsResult; 
} 

任何想法如何以優化的方式來實現這一點?

回答

1

也許您可以刪除DefaultIfEmpty並稍後添加缺少的MyClasses。

IEnumerable<MyClass> results = filteredObjectsByCodes.ToList(); 

var missing = codesToFilter 
    .Where(c => results.All(f => f.Property1 != c.Item1 && f.Property4 != c.Item2)) 
    .Select(c => new MyClass(tupleElement.Item1..); 

results = results.Union(missing); 

return new HashSet<MyClass>(results); 
+0

感謝,它是有道理的,看起來很乾淨 – 2015-02-06 20:52:31

0

在致電DefaultIfEmpty之前致電AsEnumerable。這是一個操作,首先在數據庫端執行是沒有意義的。從數據庫中獲取結果,如果爲空,則讓應用程序將默認項目添加到序列中。

爲避免在應用程序端執行Union,您只需在聯合各種數據庫查詢後應用AsEnumerable().DefaultIfEmpty(...)調用。在彙總所有子查詢之前,不需要執行DefaultIfEmpty

+0

謝謝你的回答Servy,但是,默認值應與列表中的每個元組值一起構建,如果我在聯合編輯各種DB查詢後添加DefaultIfEmpty,我得到我的默認值各自的元組值? – 2015-02-06 16:58:34