我需要根據元組值列表返回一組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;
}
任何想法如何以優化的方式來實現這一點?
感謝,它是有道理的,看起來很乾淨 – 2015-02-06 20:52:31