I'm working on a ASP .NET Core 5 MVC application with MS-SQL database and EF Core is my ORM (with the code-first approach).
Currently I'm redesigning the database, I have multiple tables that share a lot of the same properties, and I want to be able to add/remove properties from different tables, but only in one place in the code.
Because .NET doesn't have multiple class inheritance, I came up with the idea to inherit the classes in "levels". Basically, in the example below, the purchases table and the products table should have exactly the same prices, dates and content properies, but also some additional specific fields:
class Purchase : PriceDatesAndContent
{
// specific purchase properties
}
class Product : PriceDatesAndContent
{
// specific product properties
}
class PricesDatesAndContent : PriceAndDates
{
public string Name { get; set ; }
public string Description { get; set; }
}
class PricesAndDates : Prices
{
public DateTime someDate1 { get; set; }
public DateTime someDate2 { get; set; }
// ...
}
class Prices
{
public double Price1 { get; set; }
public double Price2 { get; set; }
}
However, I'm not really sure that this is really a brilliant idea as it seems to me, I would love to hear your opinion, or maybe you even have another workaround for this scenario?
Thank you very much!
CodePudding user response:
However, I'm not really sure that this is really a brilliant idea as it seems to me
Having a deep inheritance hierarchy is fine so long as your base classes aren't mapped as Entities. But it is unusual to model your classes this way just to save yourself a bit of typing.
It would probably be better to use interfaces to model the common property patterns, so you don't have to arrange them in a single hierarchy. eg
public interface IHasName
{
public string Name { get; set; }
public string Description { get; set; }
}
public interface IHasPrices
{
public double Price1 { get; set; }
public double Price2 { get; set; }
}