我需要根据元组值列表返回一组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