My model has a base class that is NOT abstract and does NOT have any key defined (it's an externally defined class that I cannot modify). Instead, I defined a derived class with MyID property to be the key. Something like this:
public class MyBaseClass // From external assembly
{
//public int ID { get; set; }
public string Name { get; set; }
}
public class MyClass // From external assembly
{
public int ID { get; set; }
public List<MyBaseClass> Objects { get; set; }
}
public class MyDerivedClass : MyBaseClass
{
public Guid MyID { get; set; }
public MyDerivedClass()
{
MyID = Guid.NewGuid();
}
}
public class MyClasses : DbContext
{
public DbSet<MyClass> Classes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyDerivedClass>().HasKey(entity => entity.MyID);
modelBuilder.Entity<MyDerivedClass>().Map(entity =>
{
entity.MapInheritedProperties();
entity.ToTable("MyBaseClass");
});
modelBuilder.Ignore<MyBaseClass>();
}
}
class Program
{
static void Main(string[] args)
{
Database.SetInitializer<MyClasses>(new DropCreateDatabaseIfModelChanges<MyClasses>());
var myClass = new MyClass() // Just as example, in real code is somethog like: MyClass myClass = ExtenalAssembly.getMyClass()
{
ID = 0,
Objects = new List<MyBaseClass>()
{
new MyBaseClass()
{
//ID = 0,
Name = "My Test Object 1"
},
new MyBaseClass()
{
//ID = 1,
Name = "My Test Object 2"
}
}
};
Mapper.CreateMap<MyBaseClass, MyDerivedClass>();
for (var index = 0; index < myClass.Objects.Count; index++)
{
myClass.Objects[index] = Mapper.Map<MyDerivedClass>(myClass.Objects[index]);
}
var myObjects = new MyClasses();
myObjects.Classes.Add(myClass);
myObjects.SaveChanges();
}
}
If I comment out the line modelBuilder.Ignore<MyBaseClass>(); the runtime throws an exception because MyBaseClass doesn't have a key defined; on the other hand, when I include that line to don't save the state of an instance of base class but only the state of an instance of derived class, the system doesn't persist any data in the generated tables.
What should I do in order to persist only the state of derived instance?