Search code examples
entity-frameworkboilerplateaspnetboilerplate

define EntityAttachment for baseEntity in order to integrate all files in one table in database


i designed a new solution based on asp.net boilerplate module-zero and i need to store attachment files that related to each entity(each row of table) in separate table in database. basically i must assumed a new entity which relate to other entity with navigation property and this approach means that each time i design new entity in this solution i have to reference it to attachment entity so i decided to design a better solution for this particular problem. i want to create a Base Class or interface for Attachment Entity named "IEntityAttachment" or "EntityAttachment" and this means that Entity class must derived from this interface or class. the question is "is this approach possible?" and "what is the best approach for this problem?"

First Approach : First Approach

Second Approach(that i want):

Second Approach


Solution

  • Yes, that approach is possible.

    First, define EntityAttachment and Attachment classes.

    public abstract class EntityAttachment : Entity {}
    
    public class Attachment : EntityAttachment
    {
        // ...
    }
    

    Next, define BaseEntity classes to reference above classes:

    public abstract class BaseEntity<TEntityAttachment> : Entity
        where TEntityAttachment : EntityAttachment
    {
        public virtual int AttachmentId { get; set; }
    
        public virtual TEntityAttachment Attachment { get; set; }
    }
    
    public abstract class BaseEntity : BaseEntity<Attachment> {}
    

    Then, define the Article, News and Slider classes:

    public class Article : BaseEntity
    {
        // ...
    }
    
    public class News : BaseEntity
    {
        // ...
    }
    
    public class Slider : BaseEntity
    {
        // ...
    }