Search code examples
c#entity-frameworkinheritancemultiple-inheritance

Alternative to multiple inheritance in Entity Framework


I would like to use inheritance to enforce consistency in Entity Framework model classes. For example, if X different models all have an address, they could inherit from:

public abstract class EntityAddress
{
    [MaxLength(400)]
    [Display(Name = "Street address")]
    [DataMember]
    public string AddressLine1 { get; set; }

    [MaxLength(400)]
    [Display(Name = "Address line 2")]
    [DataMember]
    public string AddressLine2 { get; set; }

    [MaxLength(100)]
    [Display(Name = "City")]
    [DataMember]
    public string City { get; set; }

    [MaxLength(100)]
    [Display(Name = "State")]
    [DataMember]
    public string State { get; set; }

    [MaxLength(40)]
    [Display(Name = "Zip code")]
    [DataType(DataType.PostalCode)]
    [DataMember]
    public string ZipCode { get; set; }
}

This would ensure that all addresses are consistently implemented across the product (yes, if a model has two addresses, we have an issue, but I'll wave that away for the purposes of this discussion).

I would also like the ability to have a class use an unlimited number of these concepts. For example, if a model has an address and a full name, it could do this:

public class Customer : EntityAddress, EntityFullName
{

}

Multiple inheritance, however, is not supported in C#.

Does anyone have any ideas on good alternate methods to achieve what I am trying to do here? I don't believe interfaces will work because I can't embed the attributes with the properties. I don't believe a class property will work because I want the columns in the DB associated with the base classes to be in the same table as the model class properties.


Solution

  • Complex types appear to be an answer to this question (credit to Ivan Stoev).

    https://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-2-complex-types