使用接口的抽象属性行为

时间:2018-10-18 02:47:13

标签: c# entity-framework entity-framework-core ef-core-2.1

我有一个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))
                {
                    ??
                }
            }

1 个答案:

答案 0 :(得分:2)

您快到了。只需使用Combine 2 solutions即可访问属性可变元数据:

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;
}