How to create an archive of the model in ASPNET with Entity Framework?

Viewed 38

I have a base class

public class Property
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.None)]
   public int Id { get; set; }
   ...
}

A child level 1

public class Apartament : Property
{
   public int GarageQuantity { get; set; }
   ...
}

And a child level 2

public class ArchiveApartament : Apartament
{
    public string DeletedBy { get; set; }
    public string DeletedAt { get; set; }
}

When I delete the Apartament model from database, I want to send the model to ArchiveApartament table.

How I'm doing that:

In the DeleteConfirmed ActionResult, I'm passing like this:

if (apartament != null)
{
    _context.Remove(apartament);
    await _context.SaveChangesAsync();
}
    ArchiveApartament? archive = apartament as ArchiveApartament;
    archive.DeletedBy = //somevalue;
    archive.DeletedAt = DateTime.UtcNow.ToString();
    await _context.AddAsync(archive);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));

But the action is not finalized, meaning that the Apartament row is not deleted.

I also understand that I'm violating the database Id because I'm passing a duplicated item. But what can solve this problem?

This could be also an architectural problem?

0 Answers
Related