title: C# dynamic casts when using Entity Framework for insertion
body: <p>I have a database which contains tables of mapping values for a variety of objects. </p>
  
  <p>For example the <code>Colour</code> table contains <code>BLK &gt; Black, BLU &gt; BLUE, ORA &gt; ORANGE</code> etc.. and the <code>CarType</code> table contains <code>4DH &gt; Four-door hatchback, 4WD &gt; Four wheel drive</code> etc...</p>
  
  <p>I'm using Entity Framework code-first so I have a context set up something like this.</p>
  
  <pre><code>public class MappingContext : DbContext
  {
      public MappingContext ()
          : base("Mappings")
      {
      }
  
      public DbSet&lt;Colour&gt; ColourMappings { get; set; }
      public DbSet&lt;CarType&gt; CarTypeMappings { get; set; }
  }
  </code></pre>
  
  <p>Every object that relates to each table in my <code>Mapping</code> database inherits from a base class like so:</p>
  
  <pre><code>public class Mapping
  {
      public int Id { get; set; }
  
      public string OrignalValue { get; set; }
  
      public string MappedValue { get; set; }
  }
  
  public class CarType : Mapping{}
  public class Colour : Mapping{}
  </code></pre>
  
  <p>Now what I want to do is read these mappings in from an XML file filled with "Templates" which contain the mappings and insert them in the DB.</p>
  
  <p>I have the following method to do this:</p>
  
  <pre><code>public void InsertMappings(XDocument xml, string templateName, Type typeToInsert)
  {
      // Here I find the relevent mappings 
  
      using (var repo = new Repository())
      {
          var mapppings = mappings.Select(mapping =&gt; new Mapping
          {
              MappedValue = mapping.Value,
              OrignalValue = GetCode(mapping)
          });
  
          foreach (var mapping in mapppings.ToList())
          {
              var map = (typeToInsert)mapping  // &lt;&lt; This line will not compile
  
              repo.Insert(map);
          }
  
      repo.Save();
     }
  }
  </code></pre>
  
  <p>This will not complie as it doesnt recognise the attempted cast "(typeToInsert)mapping".</p>
  
  <p>So basically what I need to know is how to I cast this Mapping object to a Specific Mapping object when it comes to inserting it into the db? Or any suggestions for a better way of doing this!</p>