C# How to extend class that exist in a different dll by adding a property to it?

1.9k views Asked by At

I have n-tier application that has many layers in different assemblies. i use entity framework 6.1 and i want to add ObjectState property to the base entity to track entity states. The problem is BaseEntity is located in my domain objects dll that is database independent and i want to add ObjectState in the Entity Framework project as this property is entity framework related.How to achieve this behavior?

public enum ObjectState
{
    Unchanged,
    Added,
    Modified,
    Deleted
}
public interface IObjectState
{
    [NotMapped]
    ObjectState ObjectState { get; set; }
}
2

There are 2 answers

1
Dennis On

If you mean, that you can't implement IObjectState in BaseEntity, because it must be independent from EF specific, then you should have two sets of entities - one for domain, one for EF, and use mapping (possibly, Automapper) between these sets:

// domain entities assembly
public abstract class BaseEntity { }

// EF entities assembly
public abstract class BaseEFEntity : IObjectState

// somewhere in the code
Mapper.Map(domainEntity, efEntity);

Actually, when using layered architecture, this is a preferable way, when each layer operates its specific models.

1
godidier On

You can use the partial classes, if you can edit the code of your domain objects projects and declare the base entity as partial class.

namespace DomainNameSpace 
{
    public partial class BaseEntity
    {
        // Your properties and method
    }
}

Then in your Entity Framework project you can add the following code:

namespace DomainNameSpace 
{
    public partial class BaseEntity
    {
        public enum ObjectState
        {
            Unchanged,
            Added,
            Modified,
            Deleted
        }
        public interface IObjectState
        {
            [NotMapped]
            ObjectState ObjectState { get; set; }
        }
    }
}

Or if you can't edit the files in domain project or don't like this approach, maybe inheritance can help. In your Entity Framework project create a class like the following.

namespace YourProjectNameSpace 
{
    public class StatefulEntityClassName : BaseEntity
    {
        public enum ObjectState
        {
            Unchanged,
            Added,
            Modified,
            Deleted
        }
        public interface IObjectState
        {
            [NotMapped]
            ObjectState ObjectState { get; set; }
        }
    }
}

Hope this help.