I would like to ask how to update row that previously was stored as some specific type and should be updated to another specific type.
Let's assume I have configured Entity Framework to use Table Per Hierarchy inheritance strategy. Now, let's say I have these classes:
abstract class Package
{
public string SomeSharedValue { get; private set; }
}
class PublicPackage : Package
{
public int SomeProperty1 { get; private set; }
public Package TurnIntoPrivatePackage(int someProperty2)
{
return new PrivatePackage(someProperty2);
}
}
class PrivatePackage : Package
{
public int SomeProperty2 { get; private set; }
public Package TurnIntoPublicPackage(int SomeProperty1)
{
return new PublicPackage(SomeProperty1);
}
}
and I have configured my model in such a way:
modelBuilder.Entity<Package>(m =>
{
m.HasDiscriminator<int>("Type")
.HasValue<PublicPackage>(1)
.HasValue<PrivatePackage>(2);
});
so right now, how do I turn (update) let's say PublicPackage into PrivatePackage
Would it work if I do something like:
public async Task DoSomething(DbContext dbContext, Guid packageId){
var package = dbContext.Packages.SingleOrDefaultAsync(f => f.Id == packageId);
//now package is of type PublicPackage
var updatedPackage = package.TurnIntoPrivatePackage(someValue)
//updated package has the same Id and other values setted for private package right now but it's new (another) instance with the same id.
dbContext.Update(updatedPackage); // Can I do this? should I detach the previous instance?
await dbContext.SaveChangesAsync()
}
dbContext.UpdateAsync(modifiedPackage)