Note that there are some explanatory texts on larger screens.

plurals
  1. POEF4 Unable to cast concrete type to interface
    text
    copied!<p>Using Entity Framework LINQ, I'd like to return a parent class for every parent table and populate a property, whose type is an interface, on the parent class with one of multiple concrete implementations of an interface. Which concrete implementation should be determined at query time based on the value of a field in the parent table.</p> <p>In a very simplified example, I have 3 tables and 3 corresponding POCOs.</p> <p><strong>Simple tables for the sake of example</strong></p> <p><img src="https://i.stack.imgur.com/gDyw9.jpg" alt="Three Tables: Master and two children"></p> <p><strong>Simple classes for the sake of example</strong></p> <pre><code>internal interface IConfiguration { } internal class ConfigurationContainer { public IConfiguration Config { get; set; } } internal class ConfigurationSouth : IConfiguration { } internal class ConfigurationNorth : IConfiguration { } </code></pre> <p>Unfortunately, I loop through all the parent results and determine which subquery to use while inside the loop. Something <strong>like</strong> this block.</p> <pre><code>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(); } </code></pre> <p>Looping through each of the parent records to perform a subquery is less than optimal. I'd really like the EF LINQ to perform the query in one trip to the database as well as do the projections into my POCOs.</p> <p>I came up with this LINQ to query the database in one trip and return the projected objects such that the Config property would be populated by one of the two subqueries at querytime. Though it compiles, it throws an exception at runtime.</p> <pre><code>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(); } </code></pre> <p><strong>Exception</strong></p> <blockquote> <p>Unhandled Exception: System.NotSupportedException: Unable to cast the type 'EFTest.ConfigurationNorth' to type 'EFTest.IConfiguration'. LINQ to Entities only supports casting Entity Data Model primitive types.</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload