Reputation: 93
I have a small application that uses EF to persist my data.
At the moment I have a single 'Ticket' class that maps directly to a 'Ticket' table.
However, there is now a need to create different types of Ticket (e.g. Cruise Ticket, Airline Ticket, Train Ticket) so I'd like to refactor my code to have these 3 ticket types all inherit from a base ticket class.
Is it possible to perform this kind of refactoring whilst maintaining/modifying the existing database?
My gut feeling is that it would be almost impossible to do this without starting again from scratch by recreating my database, and then copying the data over from the existing database.
Upvotes: 2
Views: 636
Reputation: 22595
Yes it possible to perform this kind of refactoring whilst maintaining/modifying the existing database.
If you add a migration in the normal way then entity framework will add a "Discriminator" column to your Ticket
table. You may need to populate existing data with the correct value but it is nullable by default so the database update should not fail.
You can add DbSet
s to the context for CruiseTicket
, AirlineTicket
and TrainTicket
and these will return only entities of that type. Or you can use your Tickets
DbSet
to retrieve the tickets like this:
context.Tickets.OfType<CruiseTicket>().FirstOrDefault(n => n.Id == id)
This is the default Table Per Hierarchy Strategy for implementing inheritance. You may prefer Table Per Type or even Table Per Concrete Type
References:
https://stackoverflow.com/a/23426802/150342
https://stackoverflow.com/a/23423820/150342
Upvotes: 0
Reputation: 531
You have to use TableAttribute. For this case EF will create two tables related one to one
[Table("Ticket")]
class Ticket
{
[Key]
long ID{get;set;}
}
[Table("AirTicket")]
class AirTicket : Ticket
{
string SomeSpecialAirProperty{get;set;}
}
Here table Ticket will be a general list of all tikets.
Ticket ticket = db.Ticket.Where(n=>n.ID==ticketID).FirstOrDefault();
//the value of ticket will be an object of child (Air or etc Ticket) type
Upvotes: 1