Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 525
yo2011 Avatar asked Nov 01 '22 01:11

yo2011


1 Answers

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.

like image 81
godidier Avatar answered Nov 10 '22 19:11

godidier