I have a database which contains tables of mapping values for a variety of objects.
For example the Colour table contains BLK > Black, BLU > BLUE, ORA > ORANGE etc.. and the CarType table contains 4DH > Four-door hatchback, 4WD > Four wheel drive etc…
I’m using Entity Framework code-first so I have a context set up something like this.
public class MappingContext : DbContext
{
public MappingContext ()
: base("Mappings")
{
}
public DbSet<Colour> ColourMappings { get; set; }
public DbSet<CarType> CarTypeMappings { get; set; }
}
Every object that relates to each table in my Mapping database inherits from a base class like so:
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{}
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.
I have the following method to do this:
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 => new Mapping
{
MappedValue = mapping.Value,
OrignalValue = GetCode(mapping)
});
foreach (var mapping in mapppings.ToList())
{
var map = (typeToInsert)mapping // << This line will not compile
repo.Insert(map);
}
repo.Save();
}
}
This will not complie as it doesnt recognise the attempted cast “(typeToInsert)mapping”.
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!
From the looks of it you are trying to cast an instance of
Mappingas aCarTypeorColourwhich won’t work becauseMappingdoesn’t know anything about those types as it’s the base class.Your code would need to create an instance of the concrete type i.e.
typeToInsertand cast it asMapping. You could do something like:You should probably be making use of generics here as well, you could refactor your method to look like:
Usage