简体   繁体   中英

Discriminator on Base Class on Code First

I have two nearly identical tables, Person and PersonArchive. As you can imagine PersonArchive is incredibly similar to Person, it just has the addition of two extra fields. I created the class structure below, so if an additional column gets added to Person it automatically appears in PersonArchive:

public partial class Person
{
    public int PersonId { get; set; }

    public string FirstName { get; set; }

    public string Surname { get; set; }

}

public partial class PersonArchive : Person
{

    public string ArchivedBy { get; set; }

    public DateTime ArchivedAt
    {
        get
        {
            return DateTime.Now;
        }
    }

}

My solution reads the data out of Person, fills in the the extra two fields and writes it to PersonArchive. The problem is when I try reading the data out of Person I get the missing discriminator issue, whilst looking at various posts on SO, adding NotMapped to the PersonArchive resolves the issue in reading from Person but obviously it causes problems when inserting to PersonArchive.

I've checked various posts, but non of them seem to match my issue - or at least to my understanding:

Code First: Avoid discriminator column and keep inheritance

https://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application

Entity framework code first creates "discriminator" column

Entity Framework: How to avoid Discriminator column from table?

You should define another inheritance strategy. TPT - Table Per Type would be appropriate in your case. With this approach you won't event have Disciriminator column.

Table Per Hierarchy is the default inheritance strategy in Entity Framework. Also bear in mind, that TPT inheritance strategy is not yet available in ASP.NET Core

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM