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; }
}
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.