2016-02-25 102 views
0

这主要是看我是否可以找到解决此限制的方法。能够有条件地选择要选择的行

比方说,我有以下查询:

var query = (from a in db.Table 
      where a.CustomFieldId == FieldID && a.ListingId == listingID 
      select a.SomeTypeValue); 

我查询的表设置为可以在类型而有所不同自定义字段,所以它有几个列,但只使用适当的列来存储值基于该字段的选择类型。

表看起来有点像这样:

enter image description here

我希望能够选择我选择哪一列而无需重写整个查询。这可能吗?

由于提前,

回答

1

您的查询可以rewrited使用 “方法调用LINQ”:

db.Table 
    .Where(a => a.CustomFieldId == FieldID && a.ListingId == listingID) 
    .Select(x => x.SomeType); 

您可以拆分查询到哪里,选择部分则:

var result = whereQuery.Select(x => x.BoolValue); 

var result = whereQuery.Select(x => x.IntValue); 

您甚至可以将该逻辑封装到方法中:

IEnumerable<T> GetValues<T>() { 
    var query = db.Table 
     .Where(a => a.CustomFieldId == FieldID && a.ListingId == listingID); 

    if (typeof(T)==typeof(bool)) { 
    return query.Select(x => x.BoolColumn); 
    } 
    else if (typeof(T) == typeof(int)) { 
    return query.Select(x => x.IntColumn); 
    } 
    // other types here 
} 
+0

非常感谢。我想这显示了查询语法的限制。我试图用查询语法,但它给了一些编译错误。 –