virtualmic
virtualmic

Reputation: 3213

Inheritance situation not resolved properly in Entity Framework Code First

I have a Candidate class. When somebody deletes a Candidate, I want a DeletedCandidate which is derived from Candidate to be stored in a separate table.

How can I model this in EF, Code first? I think my best option is TBC, but when I use the following in Context, a System.Data.MappingException is thrown.

modelBuilder.Entity<DeletedCandidate>().Map(d => {
                d.ToTable("DeletedCandidate");
                d.MapInheritedProperties();

            });

Upvotes: 0

Views: 102

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109099

I would not use inheritance for archiving-like tasks. You will always have to make a distinction between Candidates and DeletedCandidates in your mainstream application code. With EF you'll have to do that by always retrieving candidates by OfType<Candidate>.

I would make a separate class (and table) for DeletedCandidates. Thus, you can always get to them when needed, but they never get in harm's way in the rest of your code. A drawback may be that you always have to keep the properties (and columns) of the two in sync. This could be relieved by having both classes implement a common interface (which you can easily do with code-first).

If you need to preserve foreign key relationships to DeletedCandidates it's a different story. In that case I think the best you can do is using a deleted flag (but you're going to need filtering to get the active candidates).

Just an advice :D.

Upvotes: 1

Related Questions