user1756338
user1756338

Reputation: 211

Entity framework - Inheritance for tables

How can I manage the two following tables in Entity Framework :


Order

and


OrderArchive

In this schema orders are periodically transfered from the table Order to the table OrderArchive... Neither Table Per Type nor Table Per Hierarchy seems to fit my needs... I want to share the same methods for both object types.

Note that I cannot change the database schema. Thank you for your help.

Upvotes: 2

Views: 114

Answers (1)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

Well, if you can't change the Database schema, ... you've got a huge limitation !

If you could change that, I would do an (abstract) OrderBase class, with the common Properties and Methods, and make Order and OrderArchive inherit from it.

But if you can't, the only thing I see (someone has maybe a better idea) would be

create an interface IOrder

public Interface IOrder {
   int OrderId {get;set;}
   int ProductId {get;set;}
   int Date {get;set;}
}

make Order and OrderArchive implement IOrder (that won't change Database schema)

and create an helper class with common methods.

public static class IOrderHelper {
   //a fake method
   public static IList<IOrder> GetOrderByDate(IEnumerable<IOrder> orderList, DateTime dt) {
       return orderList.Where(m => m.Date.Date == dt);
    }
}

But of course, inheritance would be much cleaner, in this case.

EDIT Maybe look for Table per Concrete Type : you might be able to inherit from an abstract class, which wouldn't be mapped in db, and your Database wouldn't be changed.

With Code First, you would have to do

modelBuilder.Entity<Order>()
    .Map(m =>
            {
                m.ToTable("Orders");
                m.MapInheritedProperties();
            });
modelBuilder.Entity<ArchiveOrder>()
    .Map(m =>
            {
                m.ToTable("ArchiveOrders");
                m.MapInheritedProperties();
            });

but I don't know what you're using (CodeFirst, ModelFirst, DatabaseFirst) ?

Upvotes: 1

Related Questions