使用實體框架LINQ,我想爲每個父表返回一個父類,並使用多個具體實現之一在父類上填充其類型爲接口的屬性的界面。基於父表中字段的值,應該在查詢時確定具體的實現。EF4無法將具體類型轉換爲接口
在一個非常簡單的例子中,我有3個表格和3個相應的POCO。
例如起見簡單的表格
簡單的類例如起見
internal interface IConfiguration
{
}
internal class ConfigurationContainer
{
public IConfiguration Config { get; set; }
}
internal class ConfigurationSouth : IConfiguration
{
}
internal class ConfigurationNorth : IConfiguration
{
}
不幸的是,我通過所有父成果環,並確定哪些子查詢在循環內部使用。有些東西像這個塊。
foreach (var configMaster in db.ConfigMasters.ToList())
{
var configContainer = new ConfigurationContainer();
if (configMaster.IsNorth)
configContainer.Config = (from x in db.ConfigNorths
select new ConfigurationNorth())
.FirstOrDefault();
else
configContainer.Config = (from x in db.ConfigSouths
select new ConfigurationSouth())
.FirstOrDefault();
}
循環瀏覽每條父記錄以執行子查詢並不理想。我真的很喜歡EF LINQ在一次訪問數據庫時執行查詢以及對我的POCO進行預測。
我想出了這個LINQ來查詢一次旅行中的數據庫並返回投影對象,這樣Config屬性就會在查詢時間由兩個子查詢之一填充。雖然它編譯,但它在運行時引發異常。
using (var db = new Entities())
{
var qry = from cfgMaster in db.ConfigMasters
let configNorth = (from x in db.ConfigNorths
select new ConfigurationNorth())
.FirstOrDefault()
let configSouth = (from x in db.ConfigSouths
select new ConfigurationSouth())
.FirstOrDefault()
select new ConfigurationContainer()
{
Config = cfgMaster.IsNorth ? configNorth : (IConfiguration) configSouth
};
var results = qry.ToList();
}
異常
未處理的異常:System.NotSupportedException:無法鑄 類型 'EFTest.ConfigurationNorth' 爲類型 'EFTest.IConfiguration'。實體僅支持投射實體數據模型基元類型。
只有當您讓兩個類都從模型的基類中派生出來時,才能這樣做。 –
:(不幸的是,看起來你是對的,如果你將其作爲答案發布,我會接受它。 –