I have an interface for some of my DB models:
public interface IBaseEntity<T> where T: struct
{
public T Id { get; set; }
public DateTime LastUpdated { get; set; }
}
And I want automatic set property LastUpdated to DateTime.Now after saving entity. This is my override of ef SaveChanges method:
public override int SaveChanges()
{
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is IBaseEntity<???>
/* How I can check this condition?
What I should pass in a generic?
It can be any struct (Guid or int for example).
*/
&& (
e.State == EntityState.Added
|| e.State == EntityState.Modified));
foreach (var entityEntry in entries)
{
((IBaseEntity<???>)entityEntry.Entity).LastUpdated = DateTime.Now;
}
...
Is it possible to use my interface 'IBaseEntity where T: struct' in such solution?
I don't know what I should pass in generic type, my Id can be a Guid or Int, but I can't do like this:
IBaseEntity<struct>, IBaseEntity<object>, IBaseEntity<ValueType>, IBaseEntity<int | Guid> // this is all invalid
You can extract non generic interface with LastUpdated property as a root of hierarchy and inherit IBaseEntity from it. Then you can work with this non generic interface in SaveChanges() implementation.
public interface IBaseEntity
{
DateTime LastUpdated { get; set; }
}
public interface IBaseEntity<T> : IBaseEntity where T : struct
{
T Id { get; set; }
}
I use an abstract BaseEntity class instead of an interface. BaseEntity contains the UpdatedDateTime attribute. Some of my entities inherit from this abstract class. In the context event handler I use the condition entityEntry.Entity is BaseEntity, without having to know the type of the actual entity.
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.