Search code examples
c#entity-frameworkinheritanceabstract-classpartial-classes

C# Entity Framework - Inheritance issue with partial classes


I'm having an issue here with Entity Framework 5

In my program I have a base class defined as below:

public abstract class CoreProduct
{
    public abstract decimal Price { get; set; }
    public abstract decimal CategoryID { get; set; }
    public abstract decimal Quantity { get; set; }

    public decimal CalculatePrice()
    {
       //Code to calculate the price here
    }
}

I want to have specific classes auto generated by Entity Framework to inherit from this class, so that I can calculate their prices given the quantity, etc.

So what I did was to create a new file for the normal products and did this:

public partial class Product : CoreProduct
{
    public override decimal Price { get; set; }
    public override decimal CategoryID { get; set; }
    public override decimal Quantity { get; set; }
}

But since the fields Price, CategoryID and Quantity are auto generated by Entity Framework, I have to go delete them from the file auto generated by EF, then everything works.

My problem is that every time I have to update my model at all, the code gets auto generated yet again and I have to go manually re-delete all the fields for all of the classes the inherit my CoreProduct class.

What would be the better way of achieving this so I don't have to manually delete 50 fields every time I have to update my model?


Solution

  • You can create an interface to add to all of your sub classes and create an extension method to do the actual calculations.

    For example, I have this interface:

    public interface ICoreProduct
    {
        decimal Price { get; set; }
        decimal Quantity { get; set; }
    }
    

    I created a second partial class for product to attach it to that interface

    public partial class Product : ICoreProduct
    {
    }
    

    And then create an extension method for ICoreProduct

    public static decimal CalculatePrice(this ICoreProduct product)
    {
        return product.Price * product.Quantity;
    }
    

    You should then be able to do something along those lines:

    Product prod = new Product();
    prod.Price = 2;
    prod.Quantity = 10;
    decimal price = prod.CalculatePrice();