2016-07-19 68 views
0

的價值我有我的描述模型中的POCO類:LINQ2SQL得到動態選擇列

public class Example 
{ 
    public string Prop1 { get; set; } 
    public string Prop2 { get; set; } 
    public string Prop3 { get; set; } 
} 

我試圖做的是一個擴展方法到項目我的課這種方式使用實體框架DbSets:

var qry = db.Examples.Select(x => new { 
    Prop1 = x.Prop1, 
    Prop2 = x.Prop2, 
    Prop3 = x.Prop3, 
    Description = XXXXX 
}).ToList(); 

其中XXXXX是Prop1,Prop2或Prop3屬性的值,我現在只是在運行時作爲字符串。

我不能使用動態Linq,因爲我的目標是實體框架核心,並且我對LINQ表達式感到瘋狂,我想我離解決方案還很遠...... 您能否提供一些指導,請?

+0

是你同s選擇一個**單**屬性的類型** string **? –

+0

不,我需要一個投影,或者甚至是一個IQueryable 如果我在我的「示例」類中包含一個虛擬的「描述」屬性 – Vi100

+0

LINQ to Entities不允許投影到實體類型。匿名類型不能創建運行時。看看Dynamic LINQ。祝你好運。 –

回答

1

當您明確獲取Description的所有必需屬性時,可以在沒有Description的情況下獲取查詢,然後從加載的數據生成所需的查詢。

假設屬性的名稱設置Description存儲在name變量:

var qry1 = db.Examples.Select(x => new { 
    Prop1 = x.Prop1, 
    Prop2 = x.Prop2, 
    Prop3 = x.Prop3, 
}).ToList(); 
var qry = qry1.Select(x => new { 
    Prop1 = x.Prop1, 
    Prop2 = x.Prop2, 
    Prop3 = x.Prop3, 
    Description = name == "Prop1"? x.Prop1 : name == "Prop2"? x.Prop2: x.Prop3 
}).ToList(); 

如果你不喜歡硬編碼的名字,你可以使用反射來獲取值:

Description = GetProp(x, name) 

其中GetProp是:

private string GetProp(object y, string name) 
{ 
    return y.GetType().GetProperty(name).GetValue(y).ToString(); 
} 
+0

在閱讀您的答案之前,我得出了同樣的結論。無論如何,這似乎是要走的路。我會嘗試反思,因爲這個例子是一個簡化的場景。在真正的應用程序中,我有10個屬性可供選擇,所以製作9個三元運算符表達式對我來說似乎很難... – Vi100