我有一个ITiming界面:
public interface ITiming
{
DateTime CreatedAt { get; set; }
DateTime UpdatedAt { get; set; }
}
以及一些实现它的类:
public class Post : ITiming
{
public int IdPost { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
在我的模型构建器中,我为实现ITiming的每个实体设置AfterSaveBehavior
,如下所示:
modelBuilder.Entity<Post>(entity =>
{
entity.HasKey(e => e.IdPost);
entity.Property(e => e.CreatedAt)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
});
如何为实现ITiming的所有实体CreatedAt列提取AfterSaveBehaviour?
// not sure about this
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ITiming).IsAssignableFrom(entityType.ClrType))
{
??
}
}
答案 0 :(得分:2)
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ITiming).IsAssignableFrom(entityType.ClrType))
{
entityType.FindProperty(nameof(ITiming.CreatedAt))
.AfterSaveBehavior = PropertySaveBehavior.Ignore;
}
}
或者,您可以忽略接口并应用自定义DateTime CreatedAt
属性约定:
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTime) && p.Name == "CreatedAt"))
{
property.AfterSaveBehavior = PropertySaveBehavior.Ignore;
}